WebConfigurationSettings.cs 25 KB

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