WebConfigurationManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. //
  2. // System.Web.Configuration.WebConfigurationManager.cs
  3. //
  4. // Authors:
  5. // Lluis Sanchez Gual ([email protected])
  6. // Chris Toshok ([email protected])
  7. // Marek Habersack <[email protected]>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. // Copyright (C) 2005-2009 Novell, Inc (http://www.novell.com)
  29. //
  30. #if NET_2_0
  31. using System;
  32. using System.IO;
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using System.Collections.Specialized;
  36. using System.Reflection;
  37. #if MONOWEB_DEP
  38. using Mono.Web.Util;
  39. #endif
  40. using System.Xml;
  41. using System.Configuration;
  42. using System.Configuration.Internal;
  43. using _Configuration = System.Configuration.Configuration;
  44. using System.Web.Util;
  45. using System.Threading;
  46. using System.Web.Hosting;
  47. namespace System.Web.Configuration {
  48. public static class WebConfigurationManager
  49. {
  50. sealed class ConfigPath
  51. {
  52. public string Path;
  53. public bool InAnotherApp;
  54. public ConfigPath (string path, bool inAnotherApp)
  55. {
  56. this.Path = path;
  57. this.InAnotherApp = inAnotherApp;
  58. }
  59. }
  60. const int SAVE_LOCATIONS_CHECK_INTERVAL = 6000; // milliseconds
  61. const int SECTION_CACHE_LOCK_TIMEOUT = 200; // milliseconds
  62. static readonly char[] pathTrimChars = { '/' };
  63. static readonly object suppressAppReloadLock = new object ();
  64. static readonly object saveLocationsCacheLock = new object ();
  65. // See comment for the cacheLock field at top of System.Web.Caching/Cache.cs
  66. static readonly ReaderWriterLockSlim sectionCacheLock;
  67. #if !TARGET_J2EE
  68. static IInternalConfigConfigurationFactory configFactory;
  69. static Hashtable configurations = Hashtable.Synchronized (new Hashtable ());
  70. const int MAX_CACHED_SECTIONS = 100;
  71. static LruCache<int, object> sectionCache = new LruCache<int, object> (MAX_CACHED_SECTIONS);
  72. static Hashtable configPaths = Hashtable.Synchronized (new Hashtable ());
  73. static bool suppressAppReload;
  74. #else
  75. const string AppSettingsKey = "WebConfigurationManager.AppSettings";
  76. static internal IInternalConfigConfigurationFactory configFactory
  77. {
  78. get{
  79. IInternalConfigConfigurationFactory factory = (IInternalConfigConfigurationFactory)AppDomain.CurrentDomain.GetData("WebConfigurationManager.configFactory");
  80. if (factory == null){
  81. lock (AppDomain.CurrentDomain){
  82. object initialized = AppDomain.CurrentDomain.GetData("WebConfigurationManager.configFactory.initialized");
  83. if (initialized == null){
  84. PropertyInfo prop = typeof(ConfigurationManager).GetProperty("ConfigurationFactory", BindingFlags.Static | BindingFlags.NonPublic);
  85. if (prop != null){
  86. factory = prop.GetValue(null, null) as IInternalConfigConfigurationFactory;
  87. configFactory = factory;
  88. }
  89. }
  90. }
  91. }
  92. return factory != null ? factory : configFactory;
  93. }
  94. set{
  95. AppDomain.CurrentDomain.SetData("WebConfigurationManager.configFactory", value);
  96. AppDomain.CurrentDomain.SetData("WebConfigurationManager.configFactory.initialized", true);
  97. }
  98. }
  99. static internal Hashtable configurations
  100. {
  101. get{
  102. Hashtable table = (Hashtable)AppDomain.CurrentDomain.GetData("WebConfigurationManager.configurations");
  103. if (table == null){
  104. lock (AppDomain.CurrentDomain){
  105. object initialized = AppDomain.CurrentDomain.GetData("WebConfigurationManager.configurations.initialized");
  106. if (initialized == null){
  107. table = Hashtable.Synchronized (new Hashtable (StringComparer.OrdinalIgnoreCase));
  108. configurations = table;
  109. }
  110. }
  111. }
  112. return table != null ? table : configurations;
  113. }
  114. set{
  115. AppDomain.CurrentDomain.SetData("WebConfigurationManager.configurations", value);
  116. AppDomain.CurrentDomain.SetData("WebConfigurationManager.configurations.initialized", true);
  117. }
  118. }
  119. static Dictionary <int, object> sectionCache
  120. {
  121. get
  122. {
  123. Dictionary <int, object> sectionCache = AppDomain.CurrentDomain.GetData ("sectionCache") as Dictionary <int, object>;
  124. if (sectionCache == null) {
  125. sectionCache = new Dictionary <int, object> ();
  126. AppDomain.CurrentDomain.SetData ("sectionCache", sectionCache);
  127. }
  128. return sectionCache;
  129. }
  130. set
  131. {
  132. AppDomain.CurrentDomain.SetData ("sectionCache", value);
  133. }
  134. }
  135. static internal Hashtable configPaths
  136. {
  137. get{
  138. Hashtable table = (Hashtable)AppDomain.CurrentDomain.GetData("WebConfigurationManager.configPaths");
  139. if (table == null){
  140. lock (AppDomain.CurrentDomain){
  141. object initialized = AppDomain.CurrentDomain.GetData("WebConfigurationManager.configPaths.initialized");
  142. if (initialized == null){
  143. table = Hashtable.Synchronized (new Hashtable (StringComparer.OrdinalIgnoreCase));
  144. configPaths = table;
  145. }
  146. }
  147. }
  148. return table != null ? table : configPaths;
  149. }
  150. set{
  151. AppDomain.CurrentDomain.SetData("WebConfigurationManager.configPaths", value);
  152. AppDomain.CurrentDomain.SetData("WebConfigurationManager.configPaths.initialized", true);
  153. }
  154. }
  155. #endif
  156. static Dictionary <string, DateTime> saveLocationsCache;
  157. static Timer saveLocationsTimer;
  158. static ArrayList extra_assemblies = null;
  159. static internal ArrayList ExtraAssemblies {
  160. get {
  161. if (extra_assemblies == null)
  162. extra_assemblies = new ArrayList();
  163. return extra_assemblies;
  164. }
  165. }
  166. static bool hasConfigErrors = false;
  167. static object hasConfigErrorsLock = new object ();
  168. static internal bool HasConfigErrors {
  169. get {
  170. lock (hasConfigErrorsLock) {
  171. return hasConfigErrors;
  172. }
  173. }
  174. }
  175. static WebConfigurationManager ()
  176. {
  177. configFactory = ConfigurationManager.ConfigurationFactory;
  178. _Configuration.SaveStart += ConfigurationSaveHandler;
  179. _Configuration.SaveEnd += ConfigurationSaveHandler;
  180. // Part of fix for bug #491531
  181. Type type = Type.GetType ("System.Configuration.CustomizableFileSettingsProvider, System", false);
  182. if (type != null) {
  183. FieldInfo fi = type.GetField ("webConfigurationFileMapType", BindingFlags.Static | BindingFlags.NonPublic);
  184. if (fi != null && fi.FieldType == Type.GetType ("System.Type"))
  185. fi.SetValue (null, typeof (ApplicationSettingsConfigurationFileMap));
  186. }
  187. sectionCacheLock = new ReaderWriterLockSlim ();
  188. }
  189. static void ReenableWatcherOnConfigLocation (object state)
  190. {
  191. string path = state as string;
  192. if (String.IsNullOrEmpty (path))
  193. return;
  194. DateTime lastWrite;
  195. lock (saveLocationsCacheLock) {
  196. if (!saveLocationsCache.TryGetValue (path, out lastWrite))
  197. lastWrite = DateTime.MinValue;
  198. }
  199. DateTime now = DateTime.Now;
  200. if (lastWrite == DateTime.MinValue || now.Subtract (lastWrite).TotalMilliseconds >= SAVE_LOCATIONS_CHECK_INTERVAL) {
  201. saveLocationsTimer.Dispose ();
  202. saveLocationsTimer = null;
  203. HttpApplicationFactory.EnableWatcher (VirtualPathUtility.RemoveTrailingSlash (HttpRuntime.AppDomainAppPath), "?eb.?onfig");
  204. } else
  205. saveLocationsTimer.Change (SAVE_LOCATIONS_CHECK_INTERVAL, SAVE_LOCATIONS_CHECK_INTERVAL);
  206. }
  207. static void ConfigurationSaveHandler (_Configuration sender, ConfigurationSaveEventArgs args)
  208. {
  209. try {
  210. sectionCacheLock.EnterWriteLock ();
  211. sectionCache.Clear ();
  212. } finally {
  213. sectionCacheLock.ExitWriteLock ();
  214. }
  215. lock (suppressAppReloadLock) {
  216. string rootConfigPath = WebConfigurationHost.GetWebConfigFileName (HttpRuntime.AppDomainAppPath);
  217. if (String.Compare (args.StreamPath, rootConfigPath, StringComparison.OrdinalIgnoreCase) == 0) {
  218. SuppressAppReload (args.Start);
  219. if (args.Start) {
  220. HttpApplicationFactory.DisableWatcher (VirtualPathUtility.RemoveTrailingSlash (HttpRuntime.AppDomainAppPath), "?eb.?onfig");
  221. lock (saveLocationsCacheLock) {
  222. if (saveLocationsCache == null)
  223. saveLocationsCache = new Dictionary <string, DateTime> (StringComparer.Ordinal);
  224. if (saveLocationsCache.ContainsKey (rootConfigPath))
  225. saveLocationsCache [rootConfigPath] = DateTime.Now;
  226. else
  227. saveLocationsCache.Add (rootConfigPath, DateTime.Now);
  228. if (saveLocationsTimer == null)
  229. saveLocationsTimer = new Timer (ReenableWatcherOnConfigLocation,
  230. rootConfigPath,
  231. SAVE_LOCATIONS_CHECK_INTERVAL,
  232. SAVE_LOCATIONS_CHECK_INTERVAL);
  233. }
  234. }
  235. }
  236. }
  237. }
  238. public static _Configuration OpenMachineConfiguration ()
  239. {
  240. return ConfigurationManager.OpenMachineConfiguration ();
  241. }
  242. [MonoLimitation ("locationSubPath is not handled")]
  243. public static _Configuration OpenMachineConfiguration (string locationSubPath)
  244. {
  245. return OpenMachineConfiguration ();
  246. }
  247. [MonoLimitation("Mono does not support remote configuration")]
  248. public static _Configuration OpenMachineConfiguration (string locationSubPath,
  249. string server)
  250. {
  251. if (server == null)
  252. return OpenMachineConfiguration (locationSubPath);
  253. throw new NotSupportedException ("Mono doesn't support remote configuration");
  254. }
  255. [MonoLimitation("Mono does not support remote configuration")]
  256. public static _Configuration OpenMachineConfiguration (string locationSubPath,
  257. string server,
  258. IntPtr userToken)
  259. {
  260. if (server == null)
  261. return OpenMachineConfiguration (locationSubPath);
  262. throw new NotSupportedException ("Mono doesn't support remote configuration");
  263. }
  264. [MonoLimitation("Mono does not support remote configuration")]
  265. public static _Configuration OpenMachineConfiguration (string locationSubPath,
  266. string server,
  267. string userName,
  268. string password)
  269. {
  270. if (server == null)
  271. return OpenMachineConfiguration (locationSubPath);
  272. throw new NotSupportedException ("Mono doesn't support remote configuration");
  273. }
  274. public static _Configuration OpenWebConfiguration (string path)
  275. {
  276. return OpenWebConfiguration (path, null, null, null, null, null);
  277. }
  278. public static _Configuration OpenWebConfiguration (string path, string site)
  279. {
  280. return OpenWebConfiguration (path, site, null, null, null, null);
  281. }
  282. public static _Configuration OpenWebConfiguration (string path, string site, string locationSubPath)
  283. {
  284. return OpenWebConfiguration (path, site, locationSubPath, null, null, null);
  285. }
  286. public static _Configuration OpenWebConfiguration (string path, string site, string locationSubPath, string server)
  287. {
  288. return OpenWebConfiguration (path, site, locationSubPath, server, null, null);
  289. }
  290. public static _Configuration OpenWebConfiguration (string path, string site, string locationSubPath, string server, IntPtr userToken)
  291. {
  292. return OpenWebConfiguration (path, site, locationSubPath, server, null, null);
  293. }
  294. public static _Configuration OpenWebConfiguration (string path, string site, string locationSubPath, string server, string userName, string password)
  295. {
  296. return OpenWebConfiguration (path, site, locationSubPath, server, null, null, false);
  297. }
  298. static _Configuration OpenWebConfiguration (string path, string site, string locationSubPath, string server, string userName, string password, bool fweb)
  299. {
  300. if (String.IsNullOrEmpty (path))
  301. path = "/";
  302. bool inAnotherApp = false;
  303. if (!fweb && !String.IsNullOrEmpty (path))
  304. path = FindWebConfig (path, out inAnotherApp);
  305. string confKey = path + site + locationSubPath + server + userName + password;
  306. _Configuration conf = null;
  307. conf = (_Configuration) configurations [confKey];
  308. if (conf == null) {
  309. try {
  310. conf = ConfigurationFactory.Create (typeof (WebConfigurationHost), null, path, site, locationSubPath, server, userName, password, inAnotherApp);
  311. configurations [confKey] = conf;
  312. } catch (Exception ex) {
  313. lock (hasConfigErrorsLock) {
  314. hasConfigErrors = true;
  315. }
  316. throw ex;
  317. }
  318. }
  319. return conf;
  320. }
  321. public static _Configuration OpenMappedWebConfiguration (WebConfigurationFileMap fileMap, string path)
  322. {
  323. return ConfigurationFactory.Create (typeof(WebConfigurationHost), fileMap, path);
  324. }
  325. public static _Configuration OpenMappedWebConfiguration (WebConfigurationFileMap fileMap, string path, string site)
  326. {
  327. return ConfigurationFactory.Create (typeof(WebConfigurationHost), fileMap, path, site);
  328. }
  329. public static _Configuration OpenMappedWebConfiguration (WebConfigurationFileMap fileMap, string path, string site, string locationSubPath)
  330. {
  331. return ConfigurationFactory.Create (typeof(WebConfigurationHost), fileMap, path, site, locationSubPath);
  332. }
  333. public static _Configuration OpenMappedMachineConfiguration (ConfigurationFileMap fileMap)
  334. {
  335. return ConfigurationFactory.Create (typeof(WebConfigurationHost), fileMap);
  336. }
  337. public static _Configuration OpenMappedMachineConfiguration (ConfigurationFileMap fileMap,
  338. string locationSubPath)
  339. {
  340. return OpenMappedMachineConfiguration (fileMap);
  341. }
  342. internal static object SafeGetSection (string sectionName, Type configSectionType)
  343. {
  344. try {
  345. return GetSection (sectionName);
  346. } catch (Exception) {
  347. if (configSectionType != null)
  348. return Activator.CreateInstance (configSectionType);
  349. return null;
  350. }
  351. }
  352. internal static object SafeGetSection (string sectionName, string path, Type configSectionType)
  353. {
  354. try {
  355. return GetSection (sectionName, path);
  356. } catch (Exception) {
  357. if (configSectionType != null)
  358. return Activator.CreateInstance (configSectionType);
  359. return null;
  360. }
  361. }
  362. public static object GetSection (string sectionName)
  363. {
  364. HttpContext context = HttpContext.Current;
  365. return GetSection (sectionName, GetCurrentPath (context), context);
  366. }
  367. public static object GetSection (string sectionName, string path)
  368. {
  369. return GetSection (sectionName, path, HttpContext.Current);
  370. }
  371. static bool LookUpLocation (string relativePath, ref _Configuration defaultConfiguration)
  372. {
  373. if (String.IsNullOrEmpty (relativePath))
  374. return false;
  375. _Configuration cnew = defaultConfiguration.FindLocationConfiguration (relativePath, defaultConfiguration);
  376. if (cnew == defaultConfiguration)
  377. return false;
  378. defaultConfiguration = cnew;
  379. return true;
  380. }
  381. internal static object GetSection (string sectionName, string path, HttpContext context)
  382. {
  383. if (String.IsNullOrEmpty (sectionName))
  384. return null;
  385. _Configuration c = OpenWebConfiguration (path, null, null, null, null, null, false);
  386. string configPath = c.ConfigPath;
  387. int baseCacheKey = 0;
  388. int cacheKey;
  389. bool pathPresent = !String.IsNullOrEmpty (path);
  390. string locationPath = null;
  391. if (pathPresent)
  392. locationPath = "location_" + path;
  393. baseCacheKey = sectionName.GetHashCode ();
  394. if (configPath != null)
  395. baseCacheKey ^= configPath.GetHashCode ();
  396. try {
  397. sectionCacheLock.EnterReadLock ();
  398. object o;
  399. if (pathPresent) {
  400. cacheKey = baseCacheKey ^ locationPath.GetHashCode ();
  401. if (sectionCache.TryGetValue (cacheKey, out o))
  402. return o;
  403. cacheKey = baseCacheKey ^ path.GetHashCode ();
  404. if (sectionCache.TryGetValue (cacheKey, out o))
  405. return o;
  406. }
  407. if (sectionCache.TryGetValue (baseCacheKey, out o))
  408. return o;
  409. } finally {
  410. sectionCacheLock.ExitReadLock ();
  411. }
  412. string cachePath = null;
  413. if (pathPresent) {
  414. string relPath;
  415. if (VirtualPathUtility.IsRooted (path)) {
  416. if (path [0] == '~')
  417. relPath = path.Length > 1 ? path.Substring (2) : String.Empty;
  418. else if (path [0] == '/')
  419. relPath = path.Substring (1);
  420. else
  421. relPath = path;
  422. } else
  423. relPath = path;
  424. HttpRequest req = context != null ? context.Request : null;
  425. if (req != null) {
  426. string vdir = VirtualPathUtility.GetDirectory (req.PathNoValidation);
  427. if (vdir != null) {
  428. vdir = vdir.TrimEnd (pathTrimChars);
  429. if (String.Compare (c.ConfigPath, vdir, StringComparison.Ordinal) != 0 && LookUpLocation (vdir.Trim (pathTrimChars), ref c))
  430. cachePath = path;
  431. }
  432. }
  433. if (LookUpLocation (relPath, ref c))
  434. cachePath = locationPath;
  435. else
  436. cachePath = path;
  437. }
  438. ConfigurationSection section = c.GetSection (sectionName);
  439. if (section == null)
  440. return null;
  441. #if TARGET_J2EE
  442. object value = get_runtime_object.Invoke (section, new object [0]);
  443. if (String.CompareOrdinal ("appSettings", sectionName) == 0) {
  444. NameValueCollection collection;
  445. collection = new KeyValueMergedCollection (HttpContext.Current, (NameValueCollection) value);
  446. value = collection;
  447. }
  448. #else
  449. #if MONOWEB_DEP
  450. object value = SettingsMappingManager.MapSection (get_runtime_object.Invoke (section, new object [0]));
  451. #else
  452. object value = null;
  453. #endif
  454. #endif
  455. if (cachePath != null)
  456. cacheKey = baseCacheKey ^ cachePath.GetHashCode ();
  457. else
  458. cacheKey = baseCacheKey;
  459. AddSectionToCache (cacheKey, value);
  460. return value;
  461. }
  462. static string MapPath (HttpRequest req, string virtualPath)
  463. {
  464. if (req != null)
  465. return req.MapPath (virtualPath);
  466. string appRoot = HttpRuntime.AppDomainAppVirtualPath;
  467. if (!String.IsNullOrEmpty (appRoot) && virtualPath.StartsWith (appRoot, StringComparison.Ordinal)) {
  468. if (String.Compare (virtualPath, appRoot, StringComparison.Ordinal) == 0)
  469. return HttpRuntime.AppDomainAppPath;
  470. return UrlUtils.Combine (HttpRuntime.AppDomainAppPath, virtualPath.Substring (appRoot.Length));
  471. }
  472. return null;
  473. }
  474. static string GetParentDir (string rootPath, string curPath)
  475. {
  476. int len = curPath.Length - 1;
  477. if (len > 0 && curPath [len] == '/')
  478. curPath = curPath.Substring (0, len);
  479. if (String.Compare (curPath, rootPath, StringComparison.Ordinal) == 0)
  480. return null;
  481. int idx = curPath.LastIndexOf ('/');
  482. if (idx == -1)
  483. return curPath;
  484. if (idx == 0)
  485. return "/";
  486. return curPath.Substring (0, idx);
  487. }
  488. internal static string FindWebConfig (string path)
  489. {
  490. bool dummy;
  491. return FindWebConfig (path, out dummy);
  492. }
  493. internal static string FindWebConfig (string path, out bool inAnotherApp)
  494. {
  495. inAnotherApp = false;
  496. if (String.IsNullOrEmpty (path))
  497. return path;
  498. if (HostingEnvironment.VirtualPathProvider != null) {
  499. if (HostingEnvironment.VirtualPathProvider.DirectoryExists (path))
  500. path = VirtualPathUtility.AppendTrailingSlash (path);
  501. }
  502. string rootPath = HttpRuntime.AppDomainAppVirtualPath;
  503. ConfigPath curPath;
  504. curPath = configPaths [path] as ConfigPath;
  505. if (curPath != null) {
  506. inAnotherApp = curPath.InAnotherApp;
  507. return curPath.Path;
  508. }
  509. HttpContext ctx = HttpContext.Current;
  510. HttpRequest req = ctx != null ? ctx.Request : null;
  511. string physPath = req != null ? VirtualPathUtility.AppendTrailingSlash (MapPath (req, path)) : null;
  512. string appDomainPath = HttpRuntime.AppDomainAppPath;
  513. if (physPath != null && appDomainPath != null && !physPath.StartsWith (appDomainPath, StringComparison.Ordinal))
  514. inAnotherApp = true;
  515. string dir;
  516. if (inAnotherApp || path [path.Length - 1] == '/')
  517. dir = path;
  518. else {
  519. dir = VirtualPathUtility.GetDirectory (path, false);
  520. if (dir == null)
  521. return path;
  522. }
  523. curPath = configPaths [dir] as ConfigPath;
  524. if (curPath != null) {
  525. inAnotherApp = curPath.InAnotherApp;
  526. return curPath.Path;
  527. }
  528. if (req == null)
  529. return path;
  530. curPath = new ConfigPath (path, inAnotherApp);
  531. while (String.Compare (curPath.Path, rootPath, StringComparison.Ordinal) != 0) {
  532. physPath = MapPath (req, curPath.Path);
  533. if (physPath == null) {
  534. curPath.Path = rootPath;
  535. break;
  536. }
  537. if (WebConfigurationHost.GetWebConfigFileName (physPath) != null)
  538. break;
  539. curPath.Path = GetParentDir (rootPath, curPath.Path);
  540. if (curPath.Path == null || curPath.Path == "~") {
  541. curPath.Path = rootPath;
  542. break;
  543. }
  544. }
  545. if (String.Compare (curPath.Path, path, StringComparison.Ordinal) != 0)
  546. configPaths [path] = curPath;
  547. else
  548. configPaths [dir] = curPath;
  549. return curPath.Path;
  550. }
  551. static string GetCurrentPath (HttpContext ctx)
  552. {
  553. HttpRequest req = ctx != null ? ctx.Request : null;
  554. return req != null ? req.PathNoValidation : HttpRuntime.AppDomainAppVirtualPath;
  555. }
  556. internal static bool SuppressAppReload (bool newValue)
  557. {
  558. bool ret;
  559. lock (suppressAppReloadLock) {
  560. ret = suppressAppReload;
  561. suppressAppReload = newValue;
  562. }
  563. return ret;
  564. }
  565. internal static void RemoveConfigurationFromCache (HttpContext ctx)
  566. {
  567. configurations.Remove (GetCurrentPath (ctx));
  568. }
  569. #if TARGET_J2EE || MONOWEB_DEP
  570. readonly static MethodInfo get_runtime_object = typeof (ConfigurationSection).GetMethod ("GetRuntimeObject", BindingFlags.NonPublic | BindingFlags.Instance);
  571. #endif
  572. public static object GetWebApplicationSection (string sectionName)
  573. {
  574. HttpContext ctx = HttpContext.Current;
  575. HttpRequest req = ctx != null ? ctx.Request : null;
  576. string applicationPath = req != null ? req.ApplicationPath : null;
  577. return GetSection (sectionName, String.IsNullOrEmpty (applicationPath) ? String.Empty : applicationPath);
  578. }
  579. public static NameValueCollection AppSettings {
  580. get { return ConfigurationManager.AppSettings; }
  581. }
  582. public static ConnectionStringSettingsCollection ConnectionStrings {
  583. get { return ConfigurationManager.ConnectionStrings; }
  584. }
  585. internal static IInternalConfigConfigurationFactory ConfigurationFactory {
  586. get { return configFactory; }
  587. }
  588. static void AddSectionToCache (int key, object section)
  589. {
  590. object cachedSection;
  591. try {
  592. if (!sectionCacheLock.TryEnterUpgradeableReadLock (SECTION_CACHE_LOCK_TIMEOUT))
  593. return;
  594. if (sectionCache.TryGetValue (key, out cachedSection) && cachedSection != null)
  595. return;
  596. try {
  597. if (!sectionCacheLock.TryEnterWriteLock (SECTION_CACHE_LOCK_TIMEOUT))
  598. return;
  599. sectionCache.Add (key, section);
  600. } finally {
  601. try {
  602. sectionCacheLock.ExitWriteLock ();
  603. } catch (SynchronizationLockException) {
  604. // we can ignore it here
  605. }
  606. }
  607. } finally {
  608. try {
  609. sectionCacheLock.ExitUpgradeableReadLock ();
  610. } catch (SynchronizationLockException) {
  611. // we can ignore it here
  612. }
  613. }
  614. }
  615. #region stuff copied from WebConfigurationSettings
  616. #if TARGET_J2EE
  617. static internal IConfigurationSystem oldConfig {
  618. get {
  619. return (IConfigurationSystem)AppDomain.CurrentDomain.GetData("WebConfigurationManager.oldConfig");
  620. }
  621. set {
  622. AppDomain.CurrentDomain.SetData("WebConfigurationManager.oldConfig", value);
  623. }
  624. }
  625. static Web20DefaultConfig config {
  626. get {
  627. return (Web20DefaultConfig) AppDomain.CurrentDomain.GetData ("Web20DefaultConfig.config");
  628. }
  629. set {
  630. AppDomain.CurrentDomain.SetData ("Web20DefaultConfig.config", value);
  631. }
  632. }
  633. static IInternalConfigSystem configSystem {
  634. get {
  635. return (IInternalConfigSystem) AppDomain.CurrentDomain.GetData ("IInternalConfigSystem.configSystem");
  636. }
  637. set {
  638. AppDomain.CurrentDomain.SetData ("IInternalConfigSystem.configSystem", value);
  639. }
  640. }
  641. #else
  642. static internal IConfigurationSystem oldConfig;
  643. static Web20DefaultConfig config;
  644. //static IInternalConfigSystem configSystem;
  645. #endif
  646. const BindingFlags privStatic = BindingFlags.NonPublic | BindingFlags.Static;
  647. static readonly object lockobj = new object ();
  648. internal static void Init ()
  649. {
  650. lock (lockobj) {
  651. if (config != null)
  652. return;
  653. /* deal with the ConfigurationSettings stuff */
  654. {
  655. Web20DefaultConfig settings = Web20DefaultConfig.GetInstance ();
  656. Type t = typeof (ConfigurationSettings);
  657. MethodInfo changeConfig = t.GetMethod ("ChangeConfigurationSystem",
  658. privStatic);
  659. if (changeConfig == null)
  660. throw new ConfigurationException ("Cannot find method CCS");
  661. object [] args = new object [] {settings};
  662. oldConfig = (IConfigurationSystem)changeConfig.Invoke (null, args);
  663. config = settings;
  664. config.Init ();
  665. }
  666. /* deal with the ConfigurationManager stuff */
  667. {
  668. HttpConfigurationSystem system = new HttpConfigurationSystem ();
  669. Type t = typeof (ConfigurationManager);
  670. MethodInfo changeConfig = t.GetMethod ("ChangeConfigurationSystem",
  671. privStatic);
  672. if (changeConfig == null)
  673. throw new ConfigurationException ("Cannot find method CCS");
  674. object [] args = new object [] {system};
  675. changeConfig.Invoke (null, args);
  676. //configSystem = system;
  677. }
  678. }
  679. }
  680. }
  681. class Web20DefaultConfig : IConfigurationSystem
  682. {
  683. #if TARGET_J2EE
  684. static Web20DefaultConfig instance {
  685. get {
  686. Web20DefaultConfig val = (Web20DefaultConfig)AppDomain.CurrentDomain.GetData("Web20DefaultConfig.instance");
  687. if (val == null) {
  688. val = new Web20DefaultConfig();
  689. AppDomain.CurrentDomain.SetData("Web20DefaultConfig.instance", val);
  690. }
  691. return val;
  692. }
  693. set {
  694. AppDomain.CurrentDomain.SetData("Web20DefaultConfig.instance", value);
  695. }
  696. }
  697. #else
  698. static Web20DefaultConfig instance;
  699. #endif
  700. static Web20DefaultConfig ()
  701. {
  702. instance = new Web20DefaultConfig ();
  703. }
  704. public static Web20DefaultConfig GetInstance ()
  705. {
  706. return instance;
  707. }
  708. public object GetConfig (string sectionName)
  709. {
  710. object o = WebConfigurationManager.GetWebApplicationSection (sectionName);
  711. if (o == null || o is IgnoreSection) {
  712. /* this can happen when the section
  713. * handler doesn't subclass from
  714. * ConfigurationSection. let's be
  715. * nice and try to load it using the
  716. * 1.x style routines in case there's
  717. * a 1.x section handler registered
  718. * for it.
  719. */
  720. object o1 = WebConfigurationManager.oldConfig.GetConfig (sectionName);
  721. if (o1 != null)
  722. return o1;
  723. }
  724. return o;
  725. }
  726. public void Init ()
  727. {
  728. // nothing. We need a context.
  729. }
  730. }
  731. #endregion
  732. }
  733. #endif