PageMapper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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 (HttpContext.Current, String.Concat (HttpContext.Current.Request.ApplicationPath, "/", 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(HttpContext context)
  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 (context, context.Request.ApplicationPath + "/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 (HttpContext context, string url)
  164. {
  165. return GetCachedType(context, NormalizeName(url), true);
  166. }
  167. public static Type GetObjectType (HttpContext context, string url, bool throwException) {
  168. return GetCachedType (context, NormalizeName (url), throwException);
  169. }
  170. public static Assembly GetObjectAssembly (HttpContext context, string url)
  171. {
  172. return GetCachedAssembly (context, NormalizeName (url));
  173. }
  174. public static string GetAssemblyResource (HttpContext context, string url)
  175. {
  176. return GetCachedResource (context, NormalizeName (url));
  177. }
  178. private static string GetCachedResource (HttpContext context, string url)
  179. {
  180. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
  181. return doc.GetAssemblyResourceName (context, url);
  182. }
  183. private static Assembly GetCachedAssembly (HttpContext context, string url)
  184. {
  185. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
  186. return doc.GetAssembly (context, url);
  187. }
  188. private static Type GetCachedType (HttpContext context, string url) {
  189. return GetCachedType (context, url, true);
  190. }
  191. private static Type GetCachedType (HttpContext context, string url, bool throwException)
  192. {
  193. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
  194. Type t = doc.GetType(context, url);
  195. if (t == null && throwException)
  196. throw new HttpException(404,"The requested resource (" + url + ") is not available.");
  197. return t;
  198. }
  199. #region ICachedXmlDoc interface
  200. interface ICachedXmlDoc
  201. {
  202. Type GetType (HttpContext context, string key);
  203. Assembly GetAssembly (HttpContext context, string key);
  204. string GetAssemblyResourceName (HttpContext context, string key);
  205. }
  206. #endregion
  207. #region CachedDocumentTypeStorage class
  208. class CachedDocumentTypeStorage : ICachedXmlDoc
  209. {
  210. private static readonly object _fuse = new object();
  211. public static readonly ICachedXmlDoc DEFAULT_DOC =
  212. new CachedDocumentTypeStorage(0);
  213. private static readonly int DEFAULT_PAGES_NUMBER = 25;
  214. private Hashtable _table;
  215. private CachedDocumentTypeStorage(int initTableSize)
  216. {
  217. _table = Hashtable.Synchronized(new Hashtable(initTableSize));
  218. }
  219. public CachedDocumentTypeStorage() :
  220. this(DEFAULT_PAGES_NUMBER)
  221. {}
  222. string ICachedXmlDoc.GetAssemblyResourceName (HttpContext context, string o)
  223. {
  224. return GetMetaByURL(context, o).Resource;
  225. }
  226. Type ICachedXmlDoc.GetType (HttpContext context, string o)
  227. {
  228. return GetMetaByURL(context, o).Type;
  229. }
  230. Assembly ICachedXmlDoc.GetAssembly (HttpContext context, string o)
  231. {
  232. return GetMetaByURL(context, o).Assembly;
  233. }
  234. internal IDictionaryEnumerator GetEnumerator()
  235. {
  236. return _table.GetEnumerator();
  237. }
  238. //rewamped for perfomance reasons
  239. //It looks like issue is not important in development mode,
  240. //but only will became important in production mode when dynamyc compilation will be enabled
  241. //Anyway, locking whole table and compiling under lock looks odd
  242. //spivak.December 07 2006
  243. public MetaProvider GetMetaByURL(HttpContext context, string url)
  244. {
  245. #if !NO_GLOBAL_LOCK_ON_COMPILE
  246. string lwUrl = url.ToLowerInvariant();
  247. lock (_table)
  248. {
  249. object retVal = _table[lwUrl];
  250. if (retVal == null)
  251. {
  252. retVal = PageCompiler.GetCompiler(context, url);
  253. _table[lwUrl] = retVal;
  254. }
  255. return (MetaProvider)retVal;
  256. }
  257. #else
  258. string lwUrl = url.ToLower();
  259. if (!_table.ContainsKey(lwUrl))
  260. {
  261. lock (_table.SyncRoot)
  262. {
  263. if (_table.ContainsKey(lwUrl))
  264. goto Fused;
  265. _table[lwUrl] = _fuse;
  266. }
  267. try
  268. {
  269. MetaProvider meta = PageCompiler.GetCompiler(url);
  270. lock (_table.SyncRoot)
  271. {
  272. return (MetaProvider)(_table[lwUrl] = meta);
  273. }
  274. }
  275. catch(Exception e)
  276. {
  277. _table.Remove(lwUrl);
  278. }
  279. }
  280. Fused:
  281. while (_table[lwUrl] == _fuse)
  282. Thread.Sleep(10);
  283. return !_table.ContainsKey(lwUrl)? PageCompiler.Error: (MetaProvider)_table[lwUrl];
  284. #endif
  285. }
  286. }
  287. #endregion
  288. }
  289. public interface MetaProvider
  290. {
  291. Type Type { get;}
  292. Assembly Assembly {get;}
  293. string Resource { get;}
  294. }
  295. public class PageCompiler : MetaProvider
  296. {
  297. private static readonly string PAGE_XPATH = "preserve";
  298. private static readonly string ASSEM_ATTRIB_NAME = "assem";
  299. private static readonly string TYPE_ATTRIB_NAME = "type";
  300. private static string _parser = null;
  301. private Type _type = null;
  302. private string _typeName = null;
  303. private Assembly _assembly = null;
  304. private string _origAssemblyName = null;
  305. private string _xmlDescriptor = null;
  306. private string _url = null;
  307. private string _session = null;
  308. readonly private HttpContext _context;
  309. PageCompiler(HttpContext context, string url)
  310. {
  311. _url = url;
  312. _context = context;
  313. _xmlDescriptor = GetDescFromUrl();
  314. _session = DateTime.Now.Ticks.ToString();
  315. LoadTypeAndAssem();
  316. }
  317. public static PageCompiler GetCompiler(HttpContext context, string url)
  318. {
  319. return new PageCompiler(context, url);
  320. }
  321. Type MetaProvider.Type
  322. {
  323. get{
  324. return _type;
  325. }
  326. }
  327. Assembly MetaProvider.Assembly
  328. {
  329. get{
  330. return _assembly;
  331. }
  332. }
  333. string MetaProvider.Resource
  334. {
  335. get
  336. {
  337. return _origAssemblyName != null ? _origAssemblyName + ".ghres" : "dll.ghres";
  338. }
  339. }
  340. private void LoadTypeAndAssem()
  341. {
  342. if (_assembly == null)
  343. {
  344. string typeName = GetCachedTypeName();
  345. #if DEBUG
  346. Console.WriteLine ("Loading type:" + typeName);
  347. #endif
  348. if (typeName != null)
  349. {
  350. if ((_type = Type.GetType(typeName)) != null)
  351. _assembly = _type.Assembly;
  352. else
  353. _assembly = Assembly.Load(_origAssemblyName);
  354. }
  355. }
  356. }
  357. private bool InternalCompile()
  358. {
  359. string fileName = VirtualPathUtility.GetFileName (_url);
  360. string fullFileName = (fileName.ToLower () == "global.asax") ? _url : _context.Request.MapPath (_url);
  361. #if DEBUG
  362. Console.WriteLine("fullFileName=" + fullFileName);
  363. #endif
  364. //type not found - run aspxparser
  365. if (false/*File.Exists(fullFileName) || Directory.Exists(fullFileName)*/) //dynamic compilation currently is not supported
  366. {
  367. string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
  368. if (J2EEUtils.RunProc(command) != 0)
  369. throw GetCompilerError();
  370. return true;
  371. }
  372. else
  373. {
  374. return false;
  375. //string message = "The requested resource (" + _url + ") is not available.";
  376. //throw new HttpException(404, message);
  377. }
  378. }
  379. private string GetDescriptorPath()
  380. {
  381. return String.Join("/", new string[] { "assemblies", _xmlDescriptor });
  382. }
  383. private string GetTypeNameFromAppFolder()
  384. {
  385. try
  386. {
  387. using (StreamReader sr = new StreamReader(_context.Request.MapPath("~/" + GetDescriptorPath())))
  388. {
  389. return GetTypeFromDescStream(sr.BaseStream);
  390. }
  391. }
  392. catch (Exception ex)
  393. {
  394. Console.WriteLine(ex);
  395. throw ex;
  396. }
  397. }
  398. internal string GetTypeFromResources()
  399. {
  400. string typeName = null;
  401. //if the desciptor exists in the war - get the type
  402. string descPath = GetDescriptorPath();
  403. try
  404. {
  405. #if DEBUG
  406. Console.WriteLine(descPath);
  407. #endif
  408. using (Stream fs = (Stream)IOUtils.getStreamRecursive("/" + descPath))
  409. {
  410. if (fs != null)
  411. {
  412. return GetTypeFromDescStream(fs);
  413. }
  414. }
  415. }
  416. catch (Exception ex)
  417. {
  418. #if DEBUG
  419. Console.WriteLine(ex);
  420. #endif
  421. }
  422. return null;
  423. }
  424. internal string GetCachedTypeName()
  425. {
  426. string typeName = GetTypeFromResources();
  427. if (typeName == null)
  428. {
  429. //spawn dynamic compilation and lookup typename from created folder
  430. if (InternalCompile())
  431. typeName = GetTypeNameFromAppFolder();
  432. }
  433. return typeName;
  434. }
  435. private string GetTypeName()
  436. {
  437. return String.Format("{0}, {1}", _typeName, _origAssemblyName);
  438. }
  439. private bool LoadMetaFromXmlStream(Stream fs)
  440. {
  441. if (fs != null)
  442. {
  443. try
  444. {
  445. XmlDocument descXml = new XmlDocument();
  446. descXml.Load(fs);
  447. _origAssemblyName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[ASSEM_ATTRIB_NAME].Value;
  448. _typeName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[TYPE_ATTRIB_NAME].Value;
  449. return true;
  450. }
  451. catch
  452. {
  453. #if DEBUG
  454. Console.WriteLine("Failed to load typename from stream");
  455. #endif
  456. }
  457. }
  458. return false;
  459. }
  460. private string GetTypeFromDescStream(Stream fs)
  461. {
  462. if (LoadMetaFromXmlStream(fs))
  463. return GetTypeName();
  464. return null;
  465. }
  466. private string[] GetParserCmd(bool globalAsax)
  467. {
  468. string[] cmd = null;
  469. if (globalAsax)
  470. {
  471. cmd = new string[4];
  472. cmd[3] = "/buildglobalasax";
  473. }
  474. else
  475. {
  476. cmd = new string[5];
  477. cmd[3] = "/aspxFiles:" + _url;
  478. cmd[4] = "/compilepages";
  479. }
  480. cmd[0] = GetParser();
  481. cmd[1] = "/session:" + _session;
  482. cmd[2] = "/appDir:" + (string)AppDomain.CurrentDomain.GetData(IAppDomainConfig.APP_PHYS_DIR);
  483. return cmd;
  484. }
  485. private string GetParser()
  486. {
  487. if (_parser == null)
  488. {
  489. StreamReader sr =
  490. File.OpenText (_context.Request.MapPath ("~/AspxParser.params"));
  491. _parser = sr.ReadLine();
  492. sr.Close();
  493. }
  494. return _parser;
  495. }
  496. private string GetDescFromUrl()
  497. {
  498. string fileName = VirtualPathUtility.GetFileName (_url);
  499. if (fileName.ToLower() == "global.asax")
  500. return "global.asax.xml";
  501. string id = GetIdFromUrl(_url);
  502. string[] descName = new string[3] {fileName, id, ".xml"} ;
  503. return string.Concat(descName).ToLowerInvariant();
  504. }
  505. private string GetIdFromUrl(string path)
  506. {
  507. string fileName = VirtualPathUtility.GetFileName(path);
  508. string id = string.Empty;
  509. if (VirtualPathUtility.IsAbsolute (path))
  510. path = path.Substring (_context.Request.ApplicationPath.Length + 1);
  511. if (path.Length > fileName.Length)
  512. id = "." + path.Substring(0,path.Length - fileName.Length).Replace('/','_');
  513. return id;
  514. }
  515. private Exception GetCompilerError()
  516. {
  517. string _errFile = _context.Request.MapPath ("~/" + _session + ".vmwerr");
  518. if (!File.Exists(_errFile))
  519. throw new FileNotFoundException("Internal Error",_errFile);
  520. StreamReader sr = new StreamReader(_errFile);
  521. string message = string.Empty, line = null, file = null, lineInFile = "0";
  522. while ((line = sr.ReadLine()) != null)
  523. {
  524. if (line.StartsWith("Message: "))
  525. message = line.Substring("Message: ".Length);
  526. else if (line.StartsWith("File: "))
  527. file = line.Substring("File: ".Length);
  528. else if (line.StartsWith("Line: "))
  529. lineInFile = line.Substring("Line: ".Length);
  530. }
  531. sr.Close();
  532. if (file != null)
  533. {
  534. Location loc = new Location(null);
  535. loc.Filename = file;
  536. loc.BeginLine = int.Parse(lineInFile);
  537. return new ParseException(loc,message);
  538. }
  539. if (message.IndexOf(typeof(FileNotFoundException).Name) != -1 &&
  540. message.IndexOf(_url.Trim('\\','/').Replace('/','\\')) != -1)
  541. message = "The requested resource (" + _url + ") is not available.";
  542. return new HttpException(404,(message != null ? message : string.Empty));
  543. }
  544. }
  545. }