PageMapper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. //
  2. // (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
  3. //
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. //
  24. using System;
  25. using System.Xml;
  26. using System.IO;
  27. using System.Collections;
  28. using System.Web.Compilation;
  29. using System.Collections.Specialized;
  30. using System.Threading;
  31. using vmw.common;
  32. using System.Reflection;
  33. namespace System.Web.J2EE
  34. {
  35. /// <summary>
  36. /// Class that allows reading assemblies.xml file for getting information about different types.
  37. /// </summary>
  38. public class PageMapper
  39. {
  40. private static readonly string _fileListName = "/filelist.xml";
  41. private static readonly object LOCK_GETASSEMBLIESCACHEDDOCUMENT = new object();
  42. private static readonly object LOCK_GETFROMMAPPATHCACHE = new object();
  43. static Assembly CurrentDomain_AssemblyResolve (object sender, ResolveEventArgs args)
  44. {
  45. Assembly resolvedAssembly = null;
  46. try
  47. {
  48. resolvedAssembly = GetCachedAssembly (args.Name);
  49. }
  50. catch
  51. {
  52. resolvedAssembly = null;
  53. }
  54. return resolvedAssembly;
  55. }
  56. public static string GetFromMapPathCache(string key)
  57. {
  58. Hashtable answer = null;
  59. lock(LOCK_GETFROMMAPPATHCACHE)
  60. {
  61. answer = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.MAP_PATH_CACHE);
  62. if (answer == null)
  63. {
  64. answer = new Hashtable();
  65. CachedDocumentTypeStorage storage = (CachedDocumentTypeStorage)GetAssembliesCachedDocument();
  66. IDictionaryEnumerator e = storage.GetEnumerator();
  67. e.Reset();
  68. while (e.MoveNext())
  69. {
  70. string currentFile = (string)((DictionaryEntry)e.Current).Key;
  71. answer[currentFile]= IAppDomainConfig.WAR_ROOT_SYMBOL + currentFile;
  72. }
  73. AppDomain.CurrentDomain.SetData(J2EEConsts.MAP_PATH_CACHE,answer);
  74. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (CurrentDomain_AssemblyResolve);
  75. try
  76. {
  77. //Try to load the global resources
  78. HttpContext.AppGlobalResourcesAssembly = GetCachedAssembly ("app_globalresources");
  79. }
  80. catch
  81. {
  82. }
  83. }
  84. }
  85. return (string)answer[key];
  86. }
  87. #if UNUSED
  88. // UNUSED METHOD
  89. //The method was used by runtime to force file names casesensitivity
  90. // problem. The filelist.xml file should contain correct file names,
  91. // but currently it is unused
  92. public static void LoadFileList()
  93. {
  94. Hashtable hashTable = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.FILE_LIST_FILE);
  95. if (hashTable == null)
  96. {
  97. XmlDocument doc;
  98. try
  99. {
  100. Stream fs = (Stream)IOUtils.getStream(_fileListName);
  101. if (fs == null)
  102. {
  103. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  104. return;
  105. }
  106. doc = new XmlDocument();
  107. doc.Load(fs);
  108. }
  109. catch (Exception)
  110. {
  111. // Console.WriteLine("filelist.xml was not found!!!");
  112. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  113. return;
  114. }
  115. // Console.WriteLine("filelist.xml was found!!!");
  116. if (doc != null && doc.DocumentElement.HasChildNodes)
  117. {
  118. hashTable = CollectionsUtil.CreateCaseInsensitiveHashtable();
  119. XmlNodeList nodeList = doc.DocumentElement.ChildNodes;
  120. for (int i = 0;i < nodeList.Count ; i++)
  121. {
  122. string fileName = nodeList.Item(i).InnerText;
  123. hashTable.Add(fileName,fileName);
  124. }
  125. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, hashTable);
  126. }
  127. }
  128. }
  129. #endif
  130. private static ICachedXmlDoc GetAssembliesCachedDocument()
  131. {
  132. lock(LOCK_GETASSEMBLIESCACHEDDOCUMENT)
  133. {
  134. ICachedXmlDoc doc = (ICachedXmlDoc) AppDomain.CurrentDomain.GetData(J2EEConsts.ASSEMBLIES_FILE);
  135. if (doc == null)
  136. {
  137. doc = CreateDocument();
  138. if (doc != null)
  139. AppDomain.CurrentDomain.SetData(J2EEConsts.ASSEMBLIES_FILE, doc);
  140. }
  141. return doc;
  142. }
  143. }
  144. private static String NormalizeName(string url)
  145. {
  146. #if NET_2_0
  147. url = System.Web.Util.UrlUtils.RemoveDoubleSlashes(url);
  148. #endif
  149. if (url.StartsWith(IAppDomainConfig.WAR_ROOT_SYMBOL))
  150. url = url.Substring(IAppDomainConfig.WAR_ROOT_SYMBOL.Length);
  151. return url;
  152. }
  153. private static ICachedXmlDoc CreateDocument()
  154. {
  155. return new CachedDocumentTypeStorage();
  156. }
  157. public static Type GetObjectType(string url)
  158. {
  159. return GetCachedType(NormalizeName(url), true);
  160. }
  161. public static Type GetObjectType (string url, bool throwException) {
  162. return GetCachedType (NormalizeName (url), throwException);
  163. }
  164. public static Assembly GetObjectAssembly(string url)
  165. {
  166. return GetCachedAssembly(NormalizeName(url));
  167. }
  168. public static string GetAssemblyResource(string url)
  169. {
  170. return GetCachedResource(NormalizeName(url));
  171. }
  172. private static string GetCachedResource(string url)
  173. {
  174. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  175. return doc.GetAssemblyResourceName(url);
  176. }
  177. private static Assembly GetCachedAssembly(string url)
  178. {
  179. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  180. Assembly t = doc.GetAssembly(url);
  181. if (t == null)
  182. throw new HttpException(404, "The requested resource (" + url + ") is not available.");
  183. return t;
  184. }
  185. private static Type GetCachedType (string url) {
  186. return GetCachedType (url, true);
  187. }
  188. private static Type GetCachedType (string url, bool throwException)
  189. {
  190. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument();
  191. Type t = doc.GetType(url);
  192. if (t == null && throwException)
  193. throw new HttpException(404,"The requested resource (" + url + ") is not available.");
  194. return t;
  195. }
  196. #region ICachedXmlDoc interface
  197. interface ICachedXmlDoc
  198. {
  199. Type GetType(string key);
  200. Assembly GetAssembly(string key);
  201. string GetAssemblyResourceName(string key);
  202. }
  203. #endregion
  204. #region CachedDocumentTypeStorage class
  205. class CachedDocumentTypeStorage : ICachedXmlDoc
  206. {
  207. private static readonly object _fuse = new object();
  208. public static readonly ICachedXmlDoc DEFAULT_DOC =
  209. new CachedDocumentTypeStorage(0);
  210. private static readonly int DEFAULT_PAGES_NUMBER = 25;
  211. private Hashtable _table;
  212. private CachedDocumentTypeStorage(int initTableSize)
  213. {
  214. _table = Hashtable.Synchronized(new Hashtable(initTableSize));
  215. }
  216. public CachedDocumentTypeStorage() :
  217. this(DEFAULT_PAGES_NUMBER)
  218. {}
  219. string ICachedXmlDoc.GetAssemblyResourceName(string o)
  220. {
  221. return GetMetaByURL(o).Resource;
  222. }
  223. Type ICachedXmlDoc.GetType(string o)
  224. {
  225. return GetMetaByURL(o).Type;
  226. }
  227. Assembly ICachedXmlDoc.GetAssembly(string o)
  228. {
  229. return GetMetaByURL(o).Assembly;
  230. }
  231. internal IDictionaryEnumerator GetEnumerator()
  232. {
  233. return _table.GetEnumerator();
  234. }
  235. //rewamped for perfomance reasons
  236. //It looks like issue is not important in development mode,
  237. //but only will became important in production mode when dynamyc compilation will be enabled
  238. //Anyway, locking whole table and compiling under lock looks odd
  239. //spivak.December 07 2006
  240. public MetaProvider GetMetaByURL(string url)
  241. {
  242. #if !NO_GLOBAL_LOCK_ON_COMPILE
  243. string lwUrl = url.ToLower();
  244. lock (_table)
  245. {
  246. object retVal = _table[lwUrl];
  247. if (retVal == null)
  248. {
  249. retVal = PageCompiler.GetCompiler(url);
  250. _table[lwUrl] = retVal;
  251. }
  252. return (MetaProvider)retVal;
  253. }
  254. #else
  255. string lwUrl = url.ToLower();
  256. if (!_table.ContainsKey(lwUrl))
  257. {
  258. lock (_table.SyncRoot)
  259. {
  260. if (_table.ContainsKey(lwUrl))
  261. goto Fused;
  262. _table[lwUrl] = _fuse;
  263. }
  264. try
  265. {
  266. MetaProvider meta = PageCompiler.GetCompiler(url);
  267. lock (_table.SyncRoot)
  268. {
  269. return (MetaProvider)(_table[lwUrl] = meta);
  270. }
  271. }
  272. catch(Exception e)
  273. {
  274. _table.Remove(lwUrl);
  275. }
  276. }
  277. Fused:
  278. while (_table[lwUrl] == _fuse)
  279. Thread.Sleep(10);
  280. return !_table.ContainsKey(lwUrl)? PageCompiler.Error: (MetaProvider)_table[lwUrl];
  281. #endif
  282. }
  283. }
  284. #endregion
  285. }
  286. public interface MetaProvider
  287. {
  288. Type Type { get;}
  289. Assembly Assembly {get;}
  290. string Resource { get;}
  291. }
  292. public class PageCompiler : MetaProvider
  293. {
  294. private static readonly string PAGE_XPATH = "preserve";
  295. private static readonly string ASSEM_ATTRIB_NAME = "assem";
  296. private static readonly string TYPE_ATTRIB_NAME = "type";
  297. private static string _parser = null;
  298. private static PageCompiler _errorProvider = new PageCompiler();
  299. private Type _type = null;
  300. private string _typeName = null;
  301. private Assembly _assembly = null;
  302. private string _origAssemblyName = null;
  303. private string _xmlDescriptor = null;
  304. private string _url = null;
  305. private string _session = null;
  306. PageCompiler(string url)
  307. {
  308. _url = url;
  309. _xmlDescriptor = GetDescFromUrl();
  310. _session = DateTime.Now.Ticks.ToString();
  311. LoadTypeAndAssem();
  312. }
  313. PageCompiler()
  314. {
  315. }
  316. public static PageCompiler Error
  317. {
  318. get
  319. {
  320. return _errorProvider;
  321. }
  322. }
  323. public static PageCompiler GetCompiler(string url)
  324. {
  325. try{
  326. return new PageCompiler(url);
  327. }
  328. catch(Exception e)
  329. {
  330. return Error;
  331. }
  332. }
  333. Type MetaProvider.Type
  334. {
  335. get{
  336. return _type;
  337. }
  338. }
  339. Assembly MetaProvider.Assembly
  340. {
  341. get{
  342. return _assembly;
  343. }
  344. }
  345. string MetaProvider.Resource
  346. {
  347. get
  348. {
  349. return _origAssemblyName != null ? _origAssemblyName + ".ghres" : "dll.ghres";
  350. }
  351. }
  352. private void LoadTypeAndAssem()
  353. {
  354. if (_assembly == null)
  355. {
  356. string typeName = GetCachedTypeName();
  357. if (typeName != null)
  358. {
  359. if ((_type = Type.GetType(typeName)) != null)
  360. _assembly = _type.Assembly;
  361. else
  362. _assembly = Assembly.Load(_origAssemblyName);
  363. }
  364. }
  365. }
  366. private void InternalCompile()
  367. {
  368. string fileName = Path.GetFileName(_url);
  369. string fullFileName = (fileName.ToLower() == "global.asax") ? _url : HttpContext.Current.Request.MapPath(_url);
  370. #if DEBUG
  371. Console.WriteLine("fullFileName=" + fullFileName);
  372. #endif
  373. //type not found - run aspxparser
  374. if (File.Exists(fullFileName) || Directory.Exists(fullFileName))
  375. {
  376. string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
  377. if (J2EEUtils.RunProc(command) != 0)
  378. throw GetCompilerError();
  379. }
  380. else
  381. {
  382. string message = "The requested resource (" + _url + ") is not available.";
  383. throw new HttpException(404, message);
  384. }
  385. }
  386. private string GetDescriptorPath()
  387. {
  388. return String.Join("/", new string[] { "assemblies", _xmlDescriptor });
  389. }
  390. private string GetTypeNameFromAppFolder()
  391. {
  392. try
  393. {
  394. using (StreamReader sr = new StreamReader(HttpContext.Current.Request.MapPath("/" + GetDescriptorPath())))
  395. {
  396. return GetTypeFromDescStream(sr.BaseStream);
  397. }
  398. }
  399. catch (Exception ex)
  400. {
  401. Console.WriteLine(ex);
  402. throw ex;
  403. }
  404. }
  405. internal string GetTypeFromResources()
  406. {
  407. string typeName = null;
  408. //if the desciptor exists in the war - get the type
  409. string descPath = GetDescriptorPath();
  410. try
  411. {
  412. #if DEBUG
  413. Console.WriteLine(descPath);
  414. #endif
  415. using (Stream fs = (Stream)IOUtils.getStreamRecursive("/" + descPath))
  416. {
  417. if (fs != null)
  418. {
  419. return GetTypeFromDescStream(fs);
  420. }
  421. }
  422. }
  423. catch (Exception ex)
  424. {
  425. #if DEBUG
  426. Console.WriteLine(ex);
  427. #endif
  428. }
  429. return null;
  430. }
  431. internal string GetCachedTypeName()
  432. {
  433. string typeName = GetTypeFromResources();
  434. if (typeName == null)
  435. {
  436. //spawn dynamic compilation and lookup typename from created folder
  437. InternalCompile();
  438. typeName = GetTypeNameFromAppFolder();
  439. }
  440. return typeName;
  441. }
  442. private string GetTypeName()
  443. {
  444. return String.Format("{0}, {1}", _typeName, _origAssemblyName);
  445. }
  446. private bool LoadMetaFromXmlStream(Stream fs)
  447. {
  448. if (fs != null)
  449. {
  450. try
  451. {
  452. XmlDocument descXml = new XmlDocument();
  453. descXml.Load(fs);
  454. _origAssemblyName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[ASSEM_ATTRIB_NAME].Value;
  455. _typeName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[TYPE_ATTRIB_NAME].Value;
  456. return true;
  457. }
  458. catch
  459. {
  460. #if DEBUG
  461. Console.WriteLine("Failed to load typename from stream");
  462. #endif
  463. }
  464. }
  465. return false;
  466. }
  467. private string GetTypeFromDescStream(Stream fs)
  468. {
  469. if (LoadMetaFromXmlStream(fs))
  470. return GetTypeName();
  471. return null;
  472. }
  473. private string[] GetParserCmd(bool globalAsax)
  474. {
  475. string[] cmd = null;
  476. if (globalAsax)
  477. {
  478. cmd = new string[4];
  479. cmd[3] = "/buildglobalasax";
  480. }
  481. else
  482. {
  483. cmd = new string[5];
  484. cmd[3] = "/aspxFiles:" + _url;
  485. cmd[4] = "/compilepages";
  486. }
  487. cmd[0] = GetParser();
  488. cmd[1] = "/session:" + _session;
  489. cmd[2] = "/appDir:" + (string)AppDomain.CurrentDomain.GetData(IAppDomainConfig.APP_PHYS_DIR);
  490. return cmd;
  491. }
  492. private string GetParser()
  493. {
  494. if (_parser == null)
  495. {
  496. StreamReader sr =
  497. File.OpenText(HttpContext.Current.Request.MapPath("/AspxParser.params"));
  498. _parser = sr.ReadLine();
  499. sr.Close();
  500. }
  501. return _parser;
  502. }
  503. private string GetDescFromUrl()
  504. {
  505. string fileName = Path.GetFileName(_url);
  506. if (fileName.ToLower() == "global.asax")
  507. return "global.asax.xml";
  508. string id = GetIdFromUrl(_url);
  509. string[] descName = new string[3] {fileName, id, ".xml"} ;
  510. return string.Concat(descName).ToLower();
  511. }
  512. private string GetIdFromUrl(string path)
  513. {
  514. path = path.Trim('/');
  515. string fileName = Path.GetFileName(path);
  516. string id = string.Empty;
  517. path = path.Substring (path.IndexOf ("/") + 1);
  518. if (path.Length > fileName.Length)
  519. id = "." + path.Substring(0,path.Length - fileName.Length).Replace('/','_');
  520. return id;
  521. }
  522. private Exception GetCompilerError()
  523. {
  524. string _errFile = HttpContext.Current.Request.MapPath("/" + _session + ".vmwerr");
  525. if (!File.Exists(_errFile))
  526. throw new FileNotFoundException("Internal Error",_errFile);
  527. StreamReader sr = new StreamReader(_errFile);
  528. string message = string.Empty, line = null, file = null, lineInFile = "0";
  529. while ((line = sr.ReadLine()) != null)
  530. {
  531. if (line.StartsWith("Message: "))
  532. message = line.Substring("Message: ".Length);
  533. else if (line.StartsWith("File: "))
  534. file = line.Substring("File: ".Length);
  535. else if (line.StartsWith("Line: "))
  536. lineInFile = line.Substring("Line: ".Length);
  537. }
  538. sr.Close();
  539. if (file != null)
  540. {
  541. Location loc = new Location(null);
  542. loc.Filename = file;
  543. loc.BeginLine = int.Parse(lineInFile);
  544. return new ParseException(loc,message);
  545. }
  546. if (message.IndexOf(typeof(FileNotFoundException).Name) != -1 &&
  547. message.IndexOf(_url.Trim('\\','/').Replace('/','\\')) != -1)
  548. message = "The requested resource (" + _url + ") is not available.";
  549. return new HttpException(404,(message != null ? message : string.Empty));
  550. }
  551. }
  552. }