TemplateParser.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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 AddDependency (string filename)
  280. {
  281. if (dependencies == null)
  282. dependencies = new ArrayList ();
  283. if (!dependencies.Contains (filename))
  284. dependencies.Add (filename);
  285. }
  286. internal virtual void AddAssembly (Assembly assembly, bool fullPath)
  287. {
  288. if (anames == null)
  289. anames = new Hashtable ();
  290. string name = assembly.GetName ().Name;
  291. string loc = assembly.Location;
  292. if (fullPath) {
  293. if (!assemblies.Contains (loc)) {
  294. assemblies.Add (loc);
  295. }
  296. anames [name] = loc;
  297. anames [loc] = assembly;
  298. } else {
  299. if (!assemblies.Contains (name)) {
  300. assemblies.Add (name);
  301. }
  302. anames [name] = assembly;
  303. }
  304. }
  305. internal virtual Assembly AddAssemblyByName (string name)
  306. {
  307. if (anames == null)
  308. anames = new Hashtable ();
  309. if (anames.Contains (name)) {
  310. object o = anames [name];
  311. if (o is string)
  312. o = anames [o];
  313. return (Assembly) o;
  314. }
  315. Assembly assembly = null;
  316. try {
  317. assembly = Assembly.Load (name);
  318. } catch (Exception) {
  319. try {
  320. assembly = Assembly.LoadWithPartialName (name);
  321. } catch (Exception e) {
  322. ThrowParseException ("Assembly " + name + " not found", e);
  323. }
  324. if (assembly == null)
  325. ThrowParseException ("Assembly " + name + " not found", null);
  326. }
  327. AddAssembly (assembly, true);
  328. return assembly;
  329. }
  330. internal virtual void ProcessMainAttributes (Hashtable atts)
  331. {
  332. atts.Remove ("Description"); // ignored
  333. atts.Remove ("CodeBehind"); // ignored
  334. atts.Remove ("AspCompat"); // ignored
  335. #if NET_2_0
  336. atts.Remove ("CodeFile"); // ignored
  337. #endif
  338. debug = GetBool (atts, "Debug", true);
  339. compilerOptions = GetString (atts, "CompilerOptions", "");
  340. language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
  341. strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
  342. explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
  343. string src = GetString (atts, "Src", null);
  344. if (src != null)
  345. srcAssembly = GetAssemblyFromSource (src);
  346. string inherits = GetString (atts, "Inherits", null);
  347. if (inherits != null)
  348. SetBaseType (inherits);
  349. className = GetString (atts, "ClassName", null);
  350. if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
  351. ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
  352. if (atts.Count > 0)
  353. ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
  354. }
  355. internal void SetBaseType (string type)
  356. {
  357. if (type == DefaultBaseTypeName)
  358. return;
  359. Type parent = null;
  360. if (srcAssembly != null)
  361. parent = srcAssembly.GetType (type);
  362. if (parent == null)
  363. parent = LoadType (type);
  364. if (parent == null)
  365. ThrowParseException ("Cannot find type " + type);
  366. if (!DefaultBaseType.IsAssignableFrom (parent))
  367. ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
  368. baseType = parent;
  369. }
  370. Assembly GetAssemblyFromSource (string vpath)
  371. {
  372. vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
  373. string realPath = MapPath (vpath, false);
  374. if (!File.Exists (realPath))
  375. ThrowParseException ("File " + vpath + " not found");
  376. AddDependency (realPath);
  377. CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
  378. if (result.NativeCompilerReturnValue != 0) {
  379. StreamReader reader = new StreamReader (realPath);
  380. throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
  381. }
  382. AddAssembly (result.CompiledAssembly, true);
  383. return result.CompiledAssembly;
  384. }
  385. internal abstract Type DefaultBaseType { get; }
  386. internal abstract string DefaultBaseTypeName { get; }
  387. internal abstract string DefaultDirectiveName { get; }
  388. internal string InputFile
  389. {
  390. get { return inputFile; }
  391. set { inputFile = value; }
  392. }
  393. internal string Text
  394. {
  395. get { return text; }
  396. set { text = value; }
  397. }
  398. internal Type BaseType
  399. {
  400. get {
  401. if (baseType == null)
  402. baseType = DefaultBaseType;
  403. return baseType;
  404. }
  405. }
  406. internal string ClassName {
  407. get {
  408. if (className != null)
  409. return className;
  410. className = Path.GetFileName (inputFile).Replace ('.', '_');
  411. className = className.Replace ('-', '_');
  412. className = className.Replace (' ', '_');
  413. if (Char.IsDigit(className[0])) {
  414. className = "_" + className;
  415. }
  416. return className;
  417. }
  418. }
  419. internal string PrivateBinPath {
  420. get {
  421. if (privateBinPath != null)
  422. return privateBinPath;
  423. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  424. privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
  425. return privateBinPath;
  426. }
  427. }
  428. internal ArrayList Scripts {
  429. get {
  430. if (scripts == null)
  431. scripts = new ArrayList ();
  432. return scripts;
  433. }
  434. }
  435. internal ArrayList Imports {
  436. get { return imports; }
  437. }
  438. internal ArrayList Assemblies {
  439. get {
  440. if (appAssemblyIndex != -1) {
  441. object o = assemblies [appAssemblyIndex];
  442. assemblies.RemoveAt (appAssemblyIndex);
  443. assemblies.Add (o);
  444. appAssemblyIndex = -1;
  445. }
  446. return assemblies;
  447. }
  448. }
  449. internal ArrayList Interfaces {
  450. get { return interfaces; }
  451. }
  452. internal RootBuilder RootBuilder {
  453. get { return rootBuilder; }
  454. set { rootBuilder = value; }
  455. }
  456. internal ArrayList Dependencies {
  457. get { return dependencies; }
  458. }
  459. internal string CompilerOptions {
  460. get { return compilerOptions; }
  461. }
  462. internal string Language {
  463. get { return language; }
  464. }
  465. internal bool StrictOn {
  466. get { return strictOn; }
  467. }
  468. internal bool ExplicitOn {
  469. get { return explicitOn; }
  470. }
  471. internal bool Debug {
  472. get { return debug; }
  473. }
  474. internal bool OutputCache {
  475. get { return output_cache; }
  476. }
  477. internal int OutputCacheDuration {
  478. get { return oc_duration; }
  479. }
  480. internal string OutputCacheVaryByHeader {
  481. get { return oc_header; }
  482. }
  483. internal string OutputCacheVaryByCustom {
  484. get { return oc_custom; }
  485. }
  486. internal string OutputCacheVaryByControls {
  487. get { return oc_controls; }
  488. }
  489. internal bool OutputCacheShared {
  490. get { return oc_shared; }
  491. }
  492. internal OutputCacheLocation OutputCacheLocation {
  493. get { return oc_location; }
  494. }
  495. internal string OutputCacheVaryByParam {
  496. get { return oc_param; }
  497. }
  498. internal PagesConfiguration PagesConfig {
  499. get { return PagesConfiguration.GetInstance (Context); }
  500. }
  501. }
  502. }