WebConfigurationSettings.cs 24 KB

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