WebConfigurationSettings.cs 23 KB

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