TemplateParser.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. //
  2. // System.Web.UI.TemplateParser
  3. //
  4. // Authors:
  5. // Duncan Mak ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. //
  8. // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.CodeDom.Compiler;
  32. using System.Collections;
  33. using System.IO;
  34. using System.Reflection;
  35. using System.Web;
  36. using System.Web.Compilation;
  37. using System.Web.Configuration;
  38. using System.Web.Util;
  39. namespace System.Web.UI
  40. {
  41. public abstract class TemplateParser : BaseParser
  42. {
  43. string inputFile;
  44. string text;
  45. string privateBinPath;
  46. Hashtable mainAttributes;
  47. ArrayList dependencies;
  48. ArrayList assemblies;
  49. Hashtable anames;
  50. ArrayList imports;
  51. ArrayList interfaces;
  52. ArrayList scripts;
  53. Type baseType;
  54. string className;
  55. RootBuilder rootBuilder;
  56. bool debug;
  57. string compilerOptions;
  58. string language;
  59. bool strictOn = false;
  60. bool explicitOn = false;
  61. bool output_cache;
  62. int oc_duration;
  63. string oc_header, oc_custom, oc_param, oc_controls;
  64. bool oc_shared;
  65. OutputCacheLocation oc_location;
  66. Assembly srcAssembly;
  67. int appAssemblyIndex = -1;
  68. internal TemplateParser ()
  69. {
  70. imports = new ArrayList ();
  71. imports.Add ("System");
  72. imports.Add ("System.Collections");
  73. imports.Add ("System.Collections.Specialized");
  74. imports.Add ("System.Configuration");
  75. imports.Add ("System.Text");
  76. imports.Add ("System.Text.RegularExpressions");
  77. imports.Add ("System.Web");
  78. imports.Add ("System.Web.Caching");
  79. imports.Add ("System.Web.Security");
  80. imports.Add ("System.Web.SessionState");
  81. imports.Add ("System.Web.UI");
  82. imports.Add ("System.Web.UI.WebControls");
  83. imports.Add ("System.Web.UI.HtmlControls");
  84. assemblies = new ArrayList ();
  85. foreach (string a in CompilationConfig.Assemblies)
  86. AddAssemblyByName (a);
  87. if (CompilationConfig.AssembliesInBin)
  88. AddAssembliesInBin ();
  89. language = CompilationConfig.DefaultLanguage;
  90. }
  91. internal void AddApplicationAssembly ()
  92. {
  93. string location = Context.ApplicationInstance.AssemblyLocation;
  94. if (location != typeof (TemplateParser).Assembly.Location) {
  95. appAssemblyIndex = assemblies.Add (location);
  96. }
  97. }
  98. protected abstract Type CompileIntoType ();
  99. internal virtual void HandleOptions (object obj)
  100. {
  101. }
  102. internal static string GetOneKey (Hashtable tbl)
  103. {
  104. foreach (object key in tbl.Keys)
  105. return key.ToString ();
  106. return null;
  107. }
  108. internal virtual void AddDirective (string directive, Hashtable atts)
  109. {
  110. if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
  111. if (mainAttributes != null)
  112. ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
  113. mainAttributes = atts;
  114. ProcessMainAttributes (mainAttributes);
  115. return;
  116. }
  117. int cmp = String.Compare ("Assembly", directive, true);
  118. if (cmp == 0) {
  119. string name = GetString (atts, "Name", null);
  120. string src = GetString (atts, "Src", null);
  121. if (atts.Count > 0)
  122. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  123. if (name == null && src == null)
  124. ThrowParseException ("You gotta specify Src or Name");
  125. if (name != null && src != null)
  126. ThrowParseException ("Src and Name cannot be used together");
  127. if (name != null) {
  128. AddAssemblyByName (name);
  129. } else {
  130. GetAssemblyFromSource (src);
  131. }
  132. return;
  133. }
  134. cmp = String.Compare ("Import", directive, true);
  135. if (cmp == 0) {
  136. string namesp = GetString (atts, "Namespace", null);
  137. if (atts.Count > 0)
  138. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  139. if (namesp != null && namesp != "")
  140. AddImport (namesp);
  141. return;
  142. }
  143. cmp = String.Compare ("Implements", directive, true);
  144. if (cmp == 0) {
  145. string ifacename = GetString (atts, "Interface", "");
  146. if (atts.Count > 0)
  147. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  148. Type iface = LoadType (ifacename);
  149. if (iface == null)
  150. ThrowParseException ("Cannot find type " + ifacename);
  151. if (!iface.IsInterface)
  152. ThrowParseException (iface + " is not an interface");
  153. AddInterface (iface.FullName);
  154. return;
  155. }
  156. cmp = String.Compare ("OutputCache", directive, true);
  157. if (cmp == 0) {
  158. output_cache = true;
  159. if (atts ["Duration"] == null)
  160. ThrowParseException ("The directive is missing a 'duration' attribute.");
  161. if (atts ["VaryByParam"] == null)
  162. ThrowParseException ("This directive is missing a 'VaryByParam' " +
  163. "attribute, which should be set to \"none\", \"*\", " +
  164. "or a list of name/value pairs.");
  165. foreach (DictionaryEntry entry in atts) {
  166. string key = (string) entry.Key;
  167. switch (key.ToLower ()) {
  168. case "duration":
  169. oc_duration = Int32.Parse ((string) entry.Value);
  170. if (oc_duration < 1)
  171. ThrowParseException ("The 'duration' attribute must be set " +
  172. "to a positive integer value");
  173. break;
  174. case "varybyparam":
  175. oc_param = (string) entry.Value;
  176. if (String.Compare (oc_param, "none") == 0)
  177. oc_param = null;
  178. break;
  179. case "varybyheader":
  180. oc_header = (string) entry.Value;
  181. break;
  182. case "varybycustom":
  183. oc_custom = (string) entry.Value;
  184. break;
  185. case "location":
  186. if (!(this is PageParser))
  187. goto default;
  188. try {
  189. oc_location = (OutputCacheLocation) Enum.Parse (
  190. typeof (OutputCacheLocation), (string) entry.Value, true);
  191. } catch {
  192. ThrowParseException ("The 'location' attribute is case sensitive and " +
  193. "must be one of the following values: Any, Client, " +
  194. "Downstream, Server, None, ServerAndClient.");
  195. }
  196. break;
  197. case "varybycontrol":
  198. if (this is PageParser)
  199. goto default;
  200. oc_controls = (string) entry.Value;
  201. break;
  202. case "shared":
  203. if (this is PageParser)
  204. goto default;
  205. try {
  206. oc_shared = Boolean.Parse ((string) entry.Value);
  207. } catch {
  208. ThrowParseException ("The 'shared' attribute is case sensitive" +
  209. " and must be set to 'true' or 'false'.");
  210. }
  211. break;
  212. default:
  213. ThrowParseException ("The '" + key + "' attribute is not " +
  214. "supported by the 'Outputcache' directive.");
  215. break;
  216. }
  217. }
  218. return;
  219. }
  220. ThrowParseException ("Unknown directive: " + directive);
  221. }
  222. internal Type LoadType (string typeName)
  223. {
  224. // First try loaded assemblies, then try assemblies in Bin directory.
  225. Type type = null;
  226. bool seenBin = false;
  227. Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
  228. foreach (Assembly ass in assemblies) {
  229. type = ass.GetType (typeName);
  230. if (type == null)
  231. continue;
  232. if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) {
  233. AddAssembly (ass, true);
  234. } else {
  235. seenBin = true;
  236. }
  237. AddDependency (ass.Location);
  238. return type;
  239. }
  240. if (seenBin)
  241. return null;
  242. // Load from bin
  243. if (!Directory.Exists (PrivateBinPath))
  244. return null;
  245. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  246. foreach (string s in binDlls) {
  247. Assembly binA = Assembly.LoadFrom (s);
  248. type = binA.GetType (typeName);
  249. if (type == null)
  250. continue;
  251. AddDependency (binA.Location);
  252. return type;
  253. }
  254. return null;
  255. }
  256. void AddAssembliesInBin ()
  257. {
  258. if (!Directory.Exists (PrivateBinPath))
  259. return;
  260. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  261. foreach (string s in binDlls) {
  262. assemblies.Add (s);
  263. }
  264. }
  265. internal virtual void AddInterface (string iface)
  266. {
  267. if (interfaces == null)
  268. interfaces = new ArrayList ();
  269. if (!interfaces.Contains (iface))
  270. interfaces.Add (iface);
  271. }
  272. internal virtual void AddImport (string namesp)
  273. {
  274. if (imports == null)
  275. imports = new ArrayList ();
  276. if (!imports.Contains (namesp))
  277. imports.Add (namesp);
  278. }
  279. internal virtual void AddSourceDependency (string filename)
  280. {
  281. if (dependencies != null && dependencies.Contains (filename)) {
  282. ThrowParseException ("Circular file references are not allowed. File: " + filename);
  283. }
  284. AddDependency (filename);
  285. }
  286. internal virtual void AddDependency (string filename)
  287. {
  288. if (filename == "")
  289. return;
  290. if (dependencies == null)
  291. dependencies = new ArrayList ();
  292. if (!dependencies.Contains (filename))
  293. dependencies.Add (filename);
  294. }
  295. internal virtual void AddAssembly (Assembly assembly, bool fullPath)
  296. {
  297. if (assembly.Location == "")
  298. return;
  299. if (anames == null)
  300. anames = new Hashtable ();
  301. string name = assembly.GetName ().Name;
  302. string loc = assembly.Location;
  303. if (fullPath) {
  304. if (!assemblies.Contains (loc)) {
  305. assemblies.Add (loc);
  306. }
  307. anames [name] = loc;
  308. anames [loc] = assembly;
  309. } else {
  310. if (!assemblies.Contains (name)) {
  311. assemblies.Add (name);
  312. }
  313. anames [name] = assembly;
  314. }
  315. }
  316. internal virtual Assembly AddAssemblyByName (string name)
  317. {
  318. if (anames == null)
  319. anames = new Hashtable ();
  320. if (anames.Contains (name)) {
  321. object o = anames [name];
  322. if (o is string)
  323. o = anames [o];
  324. return (Assembly) o;
  325. }
  326. Assembly assembly = null;
  327. Exception error = null;
  328. if (name.IndexOf (',') != -1) {
  329. try {
  330. assembly = Assembly.Load (name);
  331. } catch (Exception e) { error = e; }
  332. }
  333. if (assembly == null) {
  334. try {
  335. assembly = Assembly.LoadWithPartialName (name);
  336. } catch (Exception e) { error = e; }
  337. }
  338. if (assembly == null)
  339. ThrowParseException ("Assembly " + name + " not found", error);
  340. AddAssembly (assembly, true);
  341. return assembly;
  342. }
  343. internal virtual void ProcessMainAttributes (Hashtable atts)
  344. {
  345. atts.Remove ("Description"); // ignored
  346. atts.Remove ("CodeBehind"); // ignored
  347. atts.Remove ("AspCompat"); // ignored
  348. #if NET_2_0
  349. atts.Remove ("CodeFile"); // ignored
  350. #endif
  351. debug = GetBool (atts, "Debug", true);
  352. compilerOptions = GetString (atts, "CompilerOptions", "");
  353. language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
  354. strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
  355. explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
  356. string src = GetString (atts, "Src", null);
  357. if (src != null)
  358. srcAssembly = GetAssemblyFromSource (src);
  359. string inherits = GetString (atts, "Inherits", null);
  360. if (inherits != null)
  361. SetBaseType (inherits);
  362. className = GetString (atts, "ClassName", null);
  363. if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
  364. ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
  365. if (atts.Count > 0)
  366. ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
  367. }
  368. internal void SetBaseType (string type)
  369. {
  370. if (type == DefaultBaseTypeName)
  371. return;
  372. Type parent = null;
  373. if (srcAssembly != null)
  374. parent = srcAssembly.GetType (type);
  375. if (parent == null)
  376. parent = LoadType (type);
  377. if (parent == null)
  378. ThrowParseException ("Cannot find type " + type);
  379. if (!DefaultBaseType.IsAssignableFrom (parent))
  380. ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
  381. baseType = parent;
  382. }
  383. Assembly GetAssemblyFromSource (string vpath)
  384. {
  385. vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
  386. string realPath = MapPath (vpath, false);
  387. if (!File.Exists (realPath))
  388. ThrowParseException ("File " + vpath + " not found");
  389. AddSourceDependency (realPath);
  390. CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
  391. if (result.NativeCompilerReturnValue != 0) {
  392. StreamReader reader = new StreamReader (realPath);
  393. throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
  394. }
  395. AddAssembly (result.CompiledAssembly, true);
  396. return result.CompiledAssembly;
  397. }
  398. internal abstract Type DefaultBaseType { get; }
  399. internal abstract string DefaultBaseTypeName { get; }
  400. internal abstract string DefaultDirectiveName { get; }
  401. internal string InputFile
  402. {
  403. get { return inputFile; }
  404. set { inputFile = value; }
  405. }
  406. internal string Text
  407. {
  408. get { return text; }
  409. set { text = value; }
  410. }
  411. internal Type BaseType
  412. {
  413. get {
  414. if (baseType == null)
  415. baseType = DefaultBaseType;
  416. return baseType;
  417. }
  418. }
  419. internal string ClassName {
  420. get {
  421. if (className != null)
  422. return className;
  423. className = Path.GetFileName (inputFile).Replace ('.', '_');
  424. className = className.Replace ('-', '_');
  425. className = className.Replace (' ', '_');
  426. if (Char.IsDigit(className[0])) {
  427. className = "_" + className;
  428. }
  429. return className;
  430. }
  431. }
  432. internal string PrivateBinPath {
  433. get {
  434. if (privateBinPath != null)
  435. return privateBinPath;
  436. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  437. privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
  438. return privateBinPath;
  439. }
  440. }
  441. internal ArrayList Scripts {
  442. get {
  443. if (scripts == null)
  444. scripts = new ArrayList ();
  445. return scripts;
  446. }
  447. }
  448. internal ArrayList Imports {
  449. get { return imports; }
  450. }
  451. internal ArrayList Assemblies {
  452. get {
  453. if (appAssemblyIndex != -1) {
  454. object o = assemblies [appAssemblyIndex];
  455. assemblies.RemoveAt (appAssemblyIndex);
  456. assemblies.Add (o);
  457. appAssemblyIndex = -1;
  458. }
  459. return assemblies;
  460. }
  461. }
  462. internal ArrayList Interfaces {
  463. get { return interfaces; }
  464. }
  465. internal RootBuilder RootBuilder {
  466. get { return rootBuilder; }
  467. set { rootBuilder = value; }
  468. }
  469. internal ArrayList Dependencies {
  470. get { return dependencies; }
  471. set { dependencies = value; }
  472. }
  473. internal string CompilerOptions {
  474. get { return compilerOptions; }
  475. }
  476. internal string Language {
  477. get { return language; }
  478. }
  479. internal bool StrictOn {
  480. get { return strictOn; }
  481. }
  482. internal bool ExplicitOn {
  483. get { return explicitOn; }
  484. }
  485. internal bool Debug {
  486. get { return debug; }
  487. }
  488. internal bool OutputCache {
  489. get { return output_cache; }
  490. }
  491. internal int OutputCacheDuration {
  492. get { return oc_duration; }
  493. }
  494. internal string OutputCacheVaryByHeader {
  495. get { return oc_header; }
  496. }
  497. internal string OutputCacheVaryByCustom {
  498. get { return oc_custom; }
  499. }
  500. internal string OutputCacheVaryByControls {
  501. get { return oc_controls; }
  502. }
  503. internal bool OutputCacheShared {
  504. get { return oc_shared; }
  505. }
  506. internal OutputCacheLocation OutputCacheLocation {
  507. get { return oc_location; }
  508. }
  509. internal string OutputCacheVaryByParam {
  510. get { return oc_param; }
  511. }
  512. internal PagesConfiguration PagesConfig {
  513. get { return PagesConfiguration.GetInstance (Context); }
  514. }
  515. }
  516. }