PageMapper.cs 16 KB

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