WebConfigurationSettings.cs 24 KB

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