WebConfigurationSettings.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. //
  2. // System.Configuration.WebConfigurationSettings.cs
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (c) 2003,2004 Novell, Inc. (http://www.novell.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Configuration;
  31. using System.Collections;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Runtime.Remoting;
  35. using System.Web.Util;
  36. using System.Xml;
  37. namespace System.Web.Configuration
  38. {
  39. class WebConfigurationSettings
  40. {
  41. static IConfigurationSystem oldConfig;
  42. static WebDefaultConfig config;
  43. static string machineConfigPath;
  44. const BindingFlags privStatic = BindingFlags.NonPublic | BindingFlags.Static;
  45. private WebConfigurationSettings ()
  46. {
  47. }
  48. public static void Init ()
  49. {
  50. lock (typeof (WebConfigurationSettings)) {
  51. if (config != null)
  52. return;
  53. WebDefaultConfig settings = WebDefaultConfig.GetInstance ();
  54. Type t = typeof (ConfigurationSettings);
  55. MethodInfo changeConfig = t.GetMethod ("ChangeConfigurationSystem",
  56. privStatic);
  57. if (changeConfig == null)
  58. throw new ConfigurationException ("Cannot find method CCS");
  59. object [] args = new object [] {settings};
  60. oldConfig = (IConfigurationSystem) changeConfig.Invoke (null, args);
  61. config = settings;
  62. }
  63. }
  64. public static void Init (HttpContext context)
  65. {
  66. Init ();
  67. config.Init (context);
  68. }
  69. public static object GetConfig (string sectionName)
  70. {
  71. return config.GetConfig (sectionName);
  72. }
  73. public static object GetConfig (string sectionName, HttpContext context)
  74. {
  75. return config.GetConfig (sectionName, context);
  76. }
  77. public static string MachineConfigPath {
  78. get {
  79. lock (typeof (WebConfigurationSettings)) {
  80. if (machineConfigPath != null)
  81. return machineConfigPath;
  82. if (config == null)
  83. Init ();
  84. Type t = oldConfig.GetType ();
  85. MethodInfo getMC = t.GetMethod ("GetMachineConfigPath",
  86. privStatic);
  87. if (getMC == null)
  88. throw new ConfigurationException ("Cannot find method GMC");
  89. machineConfigPath = (string) getMC.Invoke (null, null);
  90. return machineConfigPath;
  91. }
  92. }
  93. }
  94. }
  95. //
  96. // class WebDefaultConfig: read configuration from machine.config file and application
  97. // config file if available.
  98. //
  99. class WebDefaultConfig : IConfigurationSystem
  100. {
  101. static WebDefaultConfig instance;
  102. Hashtable fileToConfig;
  103. HttpContext firstContext;
  104. bool initCalled;
  105. static WebDefaultConfig ()
  106. {
  107. instance = new WebDefaultConfig ();
  108. }
  109. private WebDefaultConfig ()
  110. {
  111. fileToConfig = new Hashtable ();
  112. }
  113. public static WebDefaultConfig GetInstance ()
  114. {
  115. return instance;
  116. }
  117. public object GetConfig (string sectionName)
  118. {
  119. HttpContext current = HttpContext.Current;
  120. if (current == null)
  121. current = firstContext;
  122. return GetConfig (sectionName, current);
  123. }
  124. public object GetConfig (string sectionName, HttpContext context)
  125. {
  126. if (context == null)
  127. return null;
  128. ConfigurationData config = GetConfigFromFileName (context.Request.FilePath, context);
  129. if (config == null)
  130. return null;
  131. return config.GetConfig (sectionName, context);
  132. }
  133. ConfigurationData GetConfigFromFileName (string filepath, HttpContext context)
  134. {
  135. if (filepath == "")
  136. return (ConfigurationData) fileToConfig [WebConfigurationSettings.MachineConfigPath];
  137. string dir = UrlUtils.GetDirectory (filepath);
  138. if (HttpRuntime.AppDomainAppVirtualPath.Length > dir.Length)
  139. return (ConfigurationData) fileToConfig [WebConfigurationSettings.MachineConfigPath];
  140. ConfigurationData data = (ConfigurationData) fileToConfig [dir];
  141. if (data != null)
  142. return data;
  143. string realpath = context.Request.MapPath (dir);
  144. string lower = Path.Combine (realpath, "web.config");
  145. bool isLower = File.Exists (lower);
  146. string wcfile = null;
  147. if (!isLower) {
  148. string upper = Path.Combine (realpath, "Web.config");
  149. bool isUpper = File.Exists (upper);
  150. if (isUpper)
  151. wcfile = upper;
  152. } else {
  153. wcfile = lower;
  154. }
  155. string tempDir = dir;
  156. if (tempDir == HttpRuntime.AppDomainAppVirtualPath ||
  157. tempDir + "/" == HttpRuntime.AppDomainAppVirtualPath) {
  158. tempDir = "";
  159. realpath = HttpRuntime.AppDomainAppPath;
  160. }
  161. ConfigurationData parent = GetConfigFromFileName (tempDir, context);
  162. if (wcfile == null) {
  163. data = new ConfigurationData (parent, null, realpath);
  164. data.DirName = dir;
  165. fileToConfig [dir] = data;
  166. }
  167. if (data == null) {
  168. data = new ConfigurationData (parent, wcfile);
  169. data.DirName = dir;
  170. data.LoadFromFile (wcfile);
  171. fileToConfig [dir] = data;
  172. RemotingConfiguration.Configure (wcfile);
  173. }
  174. return data;
  175. }
  176. public void Init ()
  177. {
  178. // nothing. We need a context.
  179. }
  180. public void Init (HttpContext context)
  181. {
  182. lock (this) {
  183. if (initCalled)
  184. return;
  185. firstContext = context;
  186. ConfigurationData data = new ConfigurationData ();
  187. if (!data.LoadFromFile (WebConfigurationSettings.MachineConfigPath))
  188. throw new ConfigurationException ("Cannot find " + WebConfigurationSettings.MachineConfigPath);
  189. fileToConfig [WebConfigurationSettings.MachineConfigPath] = data;
  190. initCalled = true;
  191. }
  192. }
  193. static string GetAppConfigPath ()
  194. {
  195. AppDomainSetup currentInfo = AppDomain.CurrentDomain.SetupInformation;
  196. string configFile = currentInfo.ConfigurationFile;
  197. if (configFile == null || configFile.Length == 0)
  198. return null;
  199. return configFile;
  200. }
  201. }
  202. class FileWatcherCache
  203. {
  204. Hashtable cacheTable;
  205. string path;
  206. string filename;
  207. FileSystemWatcher watcher;
  208. ConfigurationData data;
  209. public FileWatcherCache (ConfigurationData data)
  210. {
  211. this.data = data;
  212. cacheTable = Hashtable.Synchronized (new Hashtable ());
  213. this.path = Path.GetDirectoryName (data.FileName);
  214. this.filename = Path.GetFileName (data.FileName);
  215. if (!Directory.Exists (path))
  216. return;
  217. watcher = new FileSystemWatcher (this.path, this.filename);
  218. FileSystemEventHandler handler = new FileSystemEventHandler (SetChanged);
  219. watcher.Created += handler;
  220. watcher.Changed += handler;
  221. watcher.Deleted += handler;
  222. watcher.EnableRaisingEvents = true;
  223. }
  224. void SetChanged (object o, FileSystemEventArgs args)
  225. {
  226. lock (data) {
  227. if (watcher.Filter == "*.config" &&
  228. String.Compare (Path.GetFileName (args.FullPath), "web.config", true) != 0)
  229. return;
  230. cacheTable.Clear ();
  231. data.Reset ();
  232. if (args.ChangeType == WatcherChangeTypes.Created)
  233. RemotingConfiguration.Configure (args.FullPath);
  234. if (args.ChangeType != WatcherChangeTypes.Deleted)
  235. data.LoadFromFile (args.FullPath);
  236. }
  237. }
  238. public object this [string key] {
  239. get {
  240. lock (data)
  241. return cacheTable [key];
  242. }
  243. set {
  244. lock (data)
  245. cacheTable [key] = value;
  246. }
  247. }
  248. public void Close ()
  249. {
  250. if (watcher != null)
  251. watcher.EnableRaisingEvents = false;
  252. }
  253. }
  254. enum AllowDefinition
  255. {
  256. Everywhere,
  257. MachineOnly,
  258. MachineToApplication
  259. }
  260. class SectionData
  261. {
  262. public readonly string SectionName;
  263. public readonly string TypeName;
  264. public readonly bool AllowLocation;
  265. public readonly AllowDefinition AllowDefinition;
  266. public string FileName;
  267. public SectionData (string sectionName, string typeName,
  268. bool allowLocation, AllowDefinition allowDefinition)
  269. {
  270. SectionName = sectionName;
  271. TypeName = typeName;
  272. AllowLocation = allowLocation;
  273. AllowDefinition = allowDefinition;
  274. }
  275. }
  276. class ConfigurationData
  277. {
  278. ConfigurationData parent;
  279. Hashtable factories;
  280. Hashtable pending;
  281. Hashtable locations;
  282. string fileName;
  283. string dirname;
  284. string realdir;
  285. static object removedMark = new object ();
  286. static object groupMark = new object ();
  287. static object emptyMark = new object ();
  288. FileWatcherCache fileCache;
  289. static char [] forbiddenPathChars = new char [] {
  290. ';', '?', ':', '@', '&', '=', '+',
  291. '$', ',','\\', '*', '\"', '<', '>'
  292. };
  293. static string forbiddenStr = "';', '?', ':', '@', '&', '=', '+', '$', ',', '\\', '*', '\"', '<', '>'";
  294. internal FileWatcherCache FileCache {
  295. get {
  296. lock (this) {
  297. if (fileCache != null)
  298. return fileCache;
  299. fileCache = new FileWatcherCache (this);
  300. }
  301. return fileCache;
  302. }
  303. }
  304. internal string FileName {
  305. get { return fileName; }
  306. }
  307. internal ConfigurationData Parent {
  308. get { return parent; }
  309. }
  310. internal string DirName {
  311. get { return dirname; }
  312. set { dirname = value; }
  313. }
  314. internal void Reset ()
  315. {
  316. factories.Clear ();
  317. if (pending != null)
  318. pending.Clear ();
  319. if (locations != null)
  320. locations.Clear ();
  321. }
  322. public ConfigurationData () : this (null, null)
  323. {
  324. }
  325. public ConfigurationData (ConfigurationData parent, string filename)
  326. {
  327. this.parent = (parent == this) ? null : parent;
  328. this.fileName = filename;
  329. factories = new Hashtable ();
  330. }
  331. public ConfigurationData (ConfigurationData parent, string filename, string realdir)
  332. {
  333. this.parent = (parent == this) ? null : parent;
  334. this.realdir = realdir;
  335. if (filename == null) {
  336. this.fileName = Path.Combine (realdir, "*.config");
  337. } else {
  338. this.fileName = filename;
  339. }
  340. factories = new Hashtable ();
  341. }
  342. public bool LoadFromFile (string fileName)
  343. {
  344. this.fileName = fileName;
  345. if (fileName == null || !File.Exists (fileName))
  346. return false;
  347. XmlTextReader reader = null;
  348. try {
  349. FileStream fs = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  350. reader = new XmlTextReader (fs);
  351. InitRead (reader);
  352. ReadConfig (reader, false);
  353. } catch (ConfigurationException) {
  354. throw;
  355. } catch (Exception e) {
  356. throw new ConfigurationException ("Error reading " + fileName, e);
  357. } finally {
  358. if (reader != null)
  359. reader.Close();
  360. }
  361. return true;
  362. }
  363. public void LoadFromReader (XmlTextReader reader, string fakeFileName, bool isLocation)
  364. {
  365. fileName = fakeFileName;
  366. MoveToNextElement (reader);
  367. ReadConfig (reader, isLocation);
  368. }
  369. object GetHandler (string sectionName)
  370. {
  371. lock (factories) {
  372. object o = factories [sectionName];
  373. if (o == null || o == removedMark) {
  374. if (parent != null)
  375. return parent.GetHandler (sectionName);
  376. return null;
  377. }
  378. if (o is IConfigurationSectionHandler)
  379. return (IConfigurationSectionHandler) o;
  380. o = CreateNewHandler (sectionName, (SectionData) o);
  381. factories [sectionName] = o;
  382. return o;
  383. }
  384. }
  385. object CreateNewHandler (string sectionName, SectionData section)
  386. {
  387. Type t = Type.GetType (section.TypeName);
  388. if (t == null)
  389. throw new ConfigurationException ("Cannot get Type for " + section.TypeName);
  390. Type iconfig = typeof (IConfigurationSectionHandler);
  391. if (!iconfig.IsAssignableFrom (t))
  392. throw new ConfigurationException (sectionName + " does not implement " + iconfig);
  393. object o = Activator.CreateInstance (t, true);
  394. if (o == null)
  395. throw new ConfigurationException ("Cannot get instance for " + t);
  396. return o;
  397. }
  398. XmlDocument GetInnerDoc (XmlDocument doc, int i, string [] sectionPath)
  399. {
  400. if (++i >= sectionPath.Length)
  401. return doc;
  402. if (doc.DocumentElement == null)
  403. return null;
  404. XmlNode node = doc.DocumentElement.FirstChild;
  405. while (node != null) {
  406. if (node.Name == sectionPath [i]) {
  407. ConfigXmlDocument result = new ConfigXmlDocument ();
  408. result.Load (new StringReader (node.OuterXml));
  409. return GetInnerDoc (result, i, sectionPath);
  410. }
  411. node = node.NextSibling;
  412. }
  413. return null;
  414. }
  415. XmlDocument GetDocumentForSection (string sectionName)
  416. {
  417. ConfigXmlDocument doc = new ConfigXmlDocument ();
  418. if (pending == null)
  419. return doc;
  420. string [] sectionPath = sectionName.Split ('/');
  421. string outerxml = pending [sectionPath [0]] as string;
  422. if (outerxml == null)
  423. return doc;
  424. StringReader reader = new StringReader (outerxml);
  425. XmlTextReader rd = new XmlTextReader (reader);
  426. rd.MoveToContent ();
  427. doc.LoadSingleElement (fileName, rd);
  428. return GetInnerDoc (doc, 0, sectionPath);
  429. }
  430. object GetConfigInternal (string sectionName, HttpContext context, bool useLoc)
  431. {
  432. object handler = GetHandler (sectionName);
  433. IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;
  434. if (iconf == null)
  435. return handler;
  436. object parentConfig = null;
  437. if (parent != null) {
  438. if (useLoc)
  439. parentConfig = parent.GetConfig (sectionName, context);
  440. else
  441. parentConfig = parent.GetConfigOptLocation (sectionName, context, false);
  442. }
  443. XmlDocument doc = GetDocumentForSection (sectionName);
  444. if (doc == null || doc.DocumentElement == null)
  445. return parentConfig;
  446. return iconf.Create (parentConfig, fileName, doc.DocumentElement);
  447. }
  448. public object GetConfig (string sectionName, HttpContext context)
  449. {
  450. if (locations != null && dirname != null) {
  451. string reduced = UrlUtils.MakeRelative (context.Request.FilePath, dirname);
  452. string [] parts = reduced.Split ('/');
  453. Location location = null;
  454. int length = parts.Length;
  455. string target = null;
  456. for (int i = 0; i < parts.Length; i++) {
  457. if (target == null)
  458. target = parts [i];
  459. else
  460. target = target + "/" + parts [i];
  461. if (locations.ContainsKey (target)) {
  462. location = locations [target] as Location;
  463. } else if (locations.ContainsKey (target + "/*")) {
  464. location = locations [target + "/*"] as Location;
  465. }
  466. }
  467. if (location == null) {
  468. location = locations ["*"] as Location;
  469. }
  470. if (location != null && location.Config != null) {
  471. object o = location.Config.GetConfigOptLocation (sectionName, context, false);
  472. if (o != null) {
  473. return o;
  474. }
  475. }
  476. }
  477. return GetConfigOptLocation (sectionName, context, true);
  478. }
  479. object GetConfigOptLocation (string sectionName, HttpContext context, bool useLoc)
  480. {
  481. object config = this.FileCache [sectionName];
  482. if (config == emptyMark)
  483. return null;
  484. if (config != null)
  485. return config;
  486. lock (this) {
  487. config = GetConfigInternal (sectionName, context, useLoc);
  488. this.FileCache [sectionName] = (config == null) ? emptyMark : config;
  489. }
  490. return config;
  491. }
  492. private object LookForFactory (string key)
  493. {
  494. object o = factories [key];
  495. if (o != null)
  496. return o;
  497. if (parent != null)
  498. return parent.LookForFactory (key);
  499. return null;
  500. }
  501. private void InitRead (XmlTextReader reader)
  502. {
  503. reader.MoveToContent ();
  504. if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
  505. ThrowException ("Configuration file does not have a valid root element", reader);
  506. if (reader.HasAttributes)
  507. ThrowException ("Unrecognized attribute in root element", reader);
  508. MoveToNextElement (reader);
  509. }
  510. internal void MoveToNextElement (XmlTextReader reader)
  511. {
  512. while (reader.Read ()) {
  513. XmlNodeType ntype = reader.NodeType;
  514. if (ntype == XmlNodeType.Element)
  515. return;
  516. if (ntype != XmlNodeType.Whitespace &&
  517. ntype != XmlNodeType.Comment &&
  518. ntype != XmlNodeType.SignificantWhitespace &&
  519. ntype != XmlNodeType.EndElement)
  520. ThrowException ("Unrecognized element", reader);
  521. }
  522. }
  523. private void ReadSection (XmlTextReader reader, string sectionName)
  524. {
  525. string attName;
  526. string nameValue = null;
  527. string typeValue = null;
  528. string allowLoc = null, allowDef = null;
  529. bool allowLocation = true;
  530. AllowDefinition allowDefinition = AllowDefinition.Everywhere;
  531. while (reader.MoveToNextAttribute ()) {
  532. attName = reader.Name;
  533. if (attName == null)
  534. continue;
  535. if (attName == "allowLocation") {
  536. if (allowLoc != null)
  537. ThrowException ("Duplicated allowLocation attribute.", reader);
  538. allowLoc = reader.Value;
  539. allowLocation = (allowLoc == "true");
  540. if (!allowLocation && allowLoc != "false")
  541. ThrowException ("Invalid attribute value", reader);
  542. continue;
  543. }
  544. if (attName == "allowDefinition") {
  545. if (allowDef != null)
  546. ThrowException ("Duplicated allowDefinition attribute.", reader);
  547. allowDef = reader.Value;
  548. try {
  549. allowDefinition = (AllowDefinition) Enum.Parse (
  550. typeof (AllowDefinition), allowDef);
  551. } catch {
  552. ThrowException ("Invalid attribute value", reader);
  553. }
  554. continue;
  555. }
  556. if (attName == "type") {
  557. if (typeValue != null)
  558. ThrowException ("Duplicated type attribute.", reader);
  559. typeValue = reader.Value;
  560. continue;
  561. }
  562. if (attName == "name") {
  563. if (nameValue != null)
  564. ThrowException ("Duplicated name attribute.", reader);
  565. nameValue = reader.Value;
  566. if (nameValue == "location")
  567. ThrowException ("location is a reserved section name", reader);
  568. continue;
  569. }
  570. ThrowException ("Unrecognized attribute.", reader);
  571. }
  572. if (nameValue == null || typeValue == null)
  573. ThrowException ("Required attribute missing", reader);
  574. if (sectionName != null)
  575. nameValue = sectionName + '/' + nameValue;
  576. reader.MoveToElement();
  577. object o = LookForFactory (nameValue);
  578. if (o != null && o != removedMark)
  579. ThrowException ("Already have a factory for " + nameValue, reader);
  580. SectionData section = new SectionData (nameValue, typeValue, allowLocation, allowDefinition);
  581. section.FileName = fileName;
  582. factories [nameValue] = section;
  583. MoveToNextElement (reader);
  584. }
  585. private void ReadRemoveSection (XmlTextReader reader, string sectionName)
  586. {
  587. if (!reader.MoveToNextAttribute () || reader.Name != "name")
  588. ThrowException ("Unrecognized attribute.", reader);
  589. string removeValue = reader.Value;
  590. if (removeValue == null || removeValue.Length == 0)
  591. ThrowException ("Empty name to remove", reader);
  592. reader.MoveToElement ();
  593. if (sectionName != null)
  594. removeValue = sectionName + '/' + removeValue;
  595. object o = LookForFactory (removeValue);
  596. if (o != null && o == removedMark)
  597. ThrowException ("No factory for " + removeValue, reader);
  598. factories [removeValue] = removedMark;
  599. MoveToNextElement (reader);
  600. }
  601. private void ReadSectionGroup (XmlTextReader reader, string configSection)
  602. {
  603. if (!reader.MoveToNextAttribute ())
  604. ThrowException ("sectionGroup must have a 'name' attribute.", reader);
  605. if (reader.Name != "name")
  606. ThrowException ("Unrecognized attribute.", reader);
  607. if (reader.MoveToNextAttribute ())
  608. ThrowException ("Unrecognized attribute.", reader);
  609. string value = reader.Value;
  610. if (value == "location")
  611. ThrowException ("location is a reserved section name", reader);
  612. if (configSection != null)
  613. value = configSection + '/' + value;
  614. object o = LookForFactory (value);
  615. if (o != null && o != removedMark && o != groupMark)
  616. ThrowException ("Already have a factory for " + value, reader);
  617. factories [value] = groupMark;
  618. MoveToNextElement (reader);
  619. ReadSections (reader, value);
  620. }
  621. private void ReadSections (XmlTextReader reader, string configSection)
  622. {
  623. int depth = reader.Depth;
  624. while (reader.Depth == depth) {
  625. string name = reader.Name;
  626. if (name == "section") {
  627. ReadSection (reader, configSection);
  628. continue;
  629. }
  630. if (name == "remove") {
  631. ReadRemoveSection (reader, configSection);
  632. continue;
  633. }
  634. if (name == "clear") {
  635. if (reader.HasAttributes)
  636. ThrowException ("Unrecognized attribute.", reader);
  637. factories.Clear ();
  638. MoveToNextElement (reader);
  639. continue;
  640. }
  641. if (name == "sectionGroup") {
  642. ReadSectionGroup (reader, configSection);
  643. continue;
  644. }
  645. ThrowException ("Unrecognized element: " + reader.Name, reader);
  646. }
  647. }
  648. void StoreLocation (string name, XmlTextReader reader)
  649. {
  650. if (locations == null) {
  651. locations = new Hashtable ();
  652. }
  653. string path = null;
  654. bool haveAllow = false;
  655. bool allowOverride = true;
  656. while (reader.MoveToNextAttribute ()) {
  657. string att = reader.Name;
  658. if (att == "path") {
  659. if (path != null)
  660. ThrowException ("Duplicate path attribute", reader);
  661. path = reader.Value;
  662. if (path.StartsWith ("."))
  663. ThrowException ("Path cannot begin with '.'", reader);
  664. if (path.IndexOfAny (forbiddenPathChars) != -1)
  665. ThrowException ("Path cannot contain " + forbiddenStr, reader);
  666. continue;
  667. }
  668. if (att == "allowOverride") {
  669. if (haveAllow)
  670. ThrowException ("Duplicate allowOverride attribute", reader);
  671. haveAllow = true;
  672. allowOverride = (reader.Value == "true");
  673. if (!allowOverride && reader.Value != "false")
  674. ThrowException ("allowOverride must be either true or false", reader);
  675. continue;
  676. }
  677. ThrowException ("Unrecognized attribute.", reader);
  678. }
  679. Location loc = new Location (this, path, allowOverride);
  680. if (locations.ContainsKey (loc.Path))
  681. ThrowException ("Duplicated location path: " + loc.Path, reader);
  682. reader.MoveToElement ();
  683. loc.LoadFromString (reader.ReadInnerXml ());
  684. locations [loc.Path] = loc;
  685. if (!loc.AllowOverride) {
  686. XmlTextReader inner = loc.GetReader ();
  687. if (inner != null) {
  688. MoveToNextElement (inner);
  689. ReadConfig (loc.GetReader (), true);
  690. }
  691. }
  692. loc.XmlStr = null;
  693. }
  694. void StorePending (string name, XmlTextReader reader)
  695. {
  696. if (pending == null)
  697. pending = new Hashtable ();
  698. if (pending.ContainsKey (name))
  699. ThrowException ("Sections can only appear once: " + name, reader);
  700. pending [name] = reader.ReadOuterXml ();
  701. }
  702. void ReadConfig (XmlTextReader reader, bool isLocation)
  703. {
  704. int depth = reader.Depth;
  705. while (!reader.EOF && reader.Depth == depth) {
  706. string name = reader.Name;
  707. if (name == "configSections") {
  708. if (isLocation)
  709. ThrowException ("<configSections> inside <location>", reader);
  710. if (reader.HasAttributes)
  711. ThrowException ("Unrecognized attribute in <configSections>.", reader);
  712. MoveToNextElement (reader);
  713. if (reader.Depth > depth)
  714. ReadSections (reader, null);
  715. } else if (name == "location") {
  716. if (isLocation)
  717. ThrowException ("<location> inside <location>", reader);
  718. StoreLocation (name, reader);
  719. MoveToNextElement (reader);
  720. } else if (name != null && name != ""){
  721. StorePending (name, reader);
  722. MoveToNextElement (reader);
  723. } else {
  724. MoveToNextElement (reader);
  725. }
  726. }
  727. }
  728. void ThrowException (string text, XmlTextReader reader)
  729. {
  730. throw new ConfigurationException (text, fileName, reader.LineNumber);
  731. }
  732. }
  733. class Location
  734. {
  735. string path;
  736. bool allowOverride;
  737. ConfigurationData parent;
  738. ConfigurationData thisOne;
  739. string xmlstr;
  740. public Location (ConfigurationData parent, string path, bool allowOverride)
  741. {
  742. this.parent = parent;
  743. this.allowOverride = allowOverride;
  744. this.path = (path == null || path == "") ? "*" : path;
  745. }
  746. public bool AllowOverride {
  747. get { return (path != "*" || allowOverride); }
  748. }
  749. public string Path {
  750. get { return path; }
  751. }
  752. public string XmlStr {
  753. set { xmlstr = value; }
  754. }
  755. public void LoadFromString (string str)
  756. {
  757. if (str == null)
  758. throw new ArgumentNullException ("str");
  759. if (thisOne != null)
  760. throw new InvalidOperationException ();
  761. this.xmlstr = str.Trim ();
  762. if (xmlstr == "")
  763. return;
  764. XmlTextReader reader = new XmlTextReader (new StringReader (str));
  765. thisOne = new ConfigurationData (parent, parent.FileName);
  766. thisOne.LoadFromReader (reader, parent.FileName, true);
  767. }
  768. public XmlTextReader GetReader ()
  769. {
  770. if (xmlstr == "")
  771. return null;
  772. XmlTextReader reader = new XmlTextReader (new StringReader (xmlstr));
  773. return reader;
  774. }
  775. public ConfigurationData Config {
  776. get { return thisOne; }
  777. }
  778. }
  779. }