WebConfigurationSettings.cs 23 KB

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