WebConfigurationSettings.cs 24 KB

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