WebConfigurationSettings.cs 25 KB

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