TemplateParser.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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 output_cache;
  60. int oc_duration;
  61. string oc_header, oc_custom, oc_param, oc_controls;
  62. bool oc_shared;
  63. OutputCacheLocation oc_location;
  64. Assembly srcAssembly;
  65. int appAssemblyIndex = -1;
  66. internal TemplateParser ()
  67. {
  68. imports = new ArrayList ();
  69. imports.Add ("System");
  70. imports.Add ("System.Collections");
  71. imports.Add ("System.Collections.Specialized");
  72. imports.Add ("System.Configuration");
  73. imports.Add ("System.Text");
  74. imports.Add ("System.Text.RegularExpressions");
  75. imports.Add ("System.Web");
  76. imports.Add ("System.Web.Caching");
  77. imports.Add ("System.Web.Security");
  78. imports.Add ("System.Web.SessionState");
  79. imports.Add ("System.Web.UI");
  80. imports.Add ("System.Web.UI.WebControls");
  81. imports.Add ("System.Web.UI.HtmlControls");
  82. assemblies = new ArrayList ();
  83. assemblies.AddRange (CompilationConfig.Assemblies);
  84. if (CompilationConfig.AssembliesInBin)
  85. AddAssembliesInBin ();
  86. language = CompilationConfig.DefaultLanguage;
  87. }
  88. internal void AddApplicationAssembly ()
  89. {
  90. string location = Context.ApplicationInstance.AssemblyLocation;
  91. if (location != typeof (TemplateParser).Assembly.Location) {
  92. appAssemblyIndex = assemblies.Add (location);
  93. }
  94. }
  95. protected abstract Type CompileIntoType ();
  96. internal virtual void HandleOptions (object obj)
  97. {
  98. }
  99. internal static string GetOneKey (Hashtable tbl)
  100. {
  101. foreach (object key in tbl.Keys)
  102. return key.ToString ();
  103. return null;
  104. }
  105. internal virtual void AddDirective (string directive, Hashtable atts)
  106. {
  107. if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
  108. if (mainAttributes != null)
  109. ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
  110. mainAttributes = atts;
  111. ProcessMainAttributes (mainAttributes);
  112. return;
  113. }
  114. int cmp = String.Compare ("Assembly", directive, true);
  115. if (cmp == 0) {
  116. string name = GetString (atts, "Name", null);
  117. string src = GetString (atts, "Src", null);
  118. if (atts.Count > 0)
  119. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  120. if (name == null && src == null)
  121. ThrowParseException ("You gotta specify Src or Name");
  122. if (name != null && src != null)
  123. ThrowParseException ("Src and Name cannot be used together");
  124. if (name != null) {
  125. AddAssemblyByName (name);
  126. } else {
  127. GetAssemblyFromSource (src);
  128. }
  129. return;
  130. }
  131. cmp = String.Compare ("Import", directive, true);
  132. if (cmp == 0) {
  133. string namesp = GetString (atts, "Namespace", null);
  134. if (atts.Count > 0)
  135. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  136. if (namesp != null && namesp != "")
  137. AddImport (namesp);
  138. return;
  139. }
  140. cmp = String.Compare ("Implements", directive, true);
  141. if (cmp == 0) {
  142. string ifacename = GetString (atts, "Interface", "");
  143. if (atts.Count > 0)
  144. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  145. Type iface = LoadType (ifacename);
  146. if (iface == null)
  147. ThrowParseException ("Cannot find type " + ifacename);
  148. if (!iface.IsInterface)
  149. ThrowParseException (iface + " is not an interface");
  150. AddInterface (iface.FullName);
  151. return;
  152. }
  153. cmp = String.Compare ("OutputCache", directive, true);
  154. if (cmp == 0) {
  155. output_cache = true;
  156. if (atts ["Duration"] == null)
  157. ThrowParseException ("The directive is missing a 'duration' attribute.");
  158. if (atts ["VaryByParam"] == null)
  159. ThrowParseException ("This directive is missing a 'VaryByParam' " +
  160. "attribute, which should be set to \"none\", \"*\", " +
  161. "or a list of name/value pairs.");
  162. foreach (DictionaryEntry entry in atts) {
  163. string key = (string) entry.Key;
  164. switch (key.ToLower ()) {
  165. case "duration":
  166. oc_duration = Int32.Parse ((string) entry.Value);
  167. if (oc_duration < 1)
  168. ThrowParseException ("The 'duration' attribute must be set " +
  169. "to a positive integer value");
  170. break;
  171. case "varybyparam":
  172. oc_param = (string) entry.Value;
  173. if (String.Compare (oc_param, "none") == 0)
  174. oc_param = null;
  175. break;
  176. case "varybyheader":
  177. oc_header = (string) entry.Value;
  178. break;
  179. case "varybycustom":
  180. oc_custom = (string) entry.Value;
  181. break;
  182. case "location":
  183. if (!(this is PageParser))
  184. goto default;
  185. try {
  186. oc_location = (OutputCacheLocation) Enum.Parse (
  187. typeof (OutputCacheLocation), (string) entry.Value, true);
  188. } catch {
  189. ThrowParseException ("The 'location' attribute is case sensitive and " +
  190. "must be one of the following values: Any, Client, " +
  191. "Downstream, Server, None, ServerAndClient.");
  192. }
  193. break;
  194. case "varybycontrol":
  195. if (this is PageParser)
  196. goto default;
  197. oc_controls = (string) entry.Value;
  198. break;
  199. case "shared":
  200. if (this is PageParser)
  201. goto default;
  202. try {
  203. oc_shared = Boolean.Parse ((string) entry.Value);
  204. } catch {
  205. ThrowParseException ("The 'shared' attribute is case sensitive" +
  206. " and must be set to 'true' or 'false'.");
  207. }
  208. break;
  209. default:
  210. ThrowParseException ("The '" + key + "' attribute is not " +
  211. "supported by the 'Outputcache' directive.");
  212. break;
  213. }
  214. }
  215. return;
  216. }
  217. ThrowParseException ("Unknown directive: " + directive);
  218. }
  219. internal Type LoadType (string typeName)
  220. {
  221. // First try loaded assemblies, then try assemblies in Bin directory.
  222. Type type = null;
  223. bool seenBin = false;
  224. Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
  225. foreach (Assembly ass in assemblies) {
  226. type = ass.GetType (typeName);
  227. if (type == null)
  228. continue;
  229. if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) {
  230. AddAssembly (ass, false);
  231. } else {
  232. seenBin = true;
  233. }
  234. AddDependency (ass.Location);
  235. return type;
  236. }
  237. if (seenBin)
  238. return null;
  239. // Load from bin
  240. if (!Directory.Exists (PrivateBinPath))
  241. return null;
  242. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  243. foreach (string s in binDlls) {
  244. Assembly binA = Assembly.LoadFrom (s);
  245. type = binA.GetType (typeName);
  246. if (type == null)
  247. continue;
  248. AddDependency (binA.Location);
  249. return type;
  250. }
  251. return null;
  252. }
  253. void AddAssembliesInBin ()
  254. {
  255. if (!Directory.Exists (PrivateBinPath))
  256. return;
  257. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  258. foreach (string s in binDlls) {
  259. assemblies.Add (s);
  260. }
  261. }
  262. internal virtual void AddInterface (string iface)
  263. {
  264. if (interfaces == null)
  265. interfaces = new ArrayList ();
  266. if (!interfaces.Contains (iface))
  267. interfaces.Add (iface);
  268. }
  269. internal virtual void AddImport (string namesp)
  270. {
  271. if (imports == null)
  272. imports = new ArrayList ();
  273. if (!imports.Contains (namesp))
  274. imports.Add (namesp);
  275. }
  276. internal virtual void AddDependency (string filename)
  277. {
  278. if (dependencies == null)
  279. dependencies = new ArrayList ();
  280. if (!dependencies.Contains (filename))
  281. dependencies.Add (filename);
  282. }
  283. internal virtual void AddAssembly (Assembly assembly, bool fullPath)
  284. {
  285. if (anames == null)
  286. anames = new Hashtable ();
  287. string name = assembly.GetName ().Name;
  288. string loc = assembly.Location;
  289. if (fullPath) {
  290. if (!assemblies.Contains (loc)) {
  291. assemblies.Add (loc);
  292. }
  293. anames [name] = loc;
  294. anames [loc] = assembly;
  295. } else {
  296. if (!assemblies.Contains (name)) {
  297. assemblies.Add (name);
  298. }
  299. anames [name] = assembly;
  300. }
  301. }
  302. internal virtual Assembly AddAssemblyByName (string name)
  303. {
  304. if (anames == null)
  305. anames = new Hashtable ();
  306. if (anames.Contains (name)) {
  307. object o = anames [name];
  308. if (o is string)
  309. o = anames [o];
  310. return (Assembly) o;
  311. }
  312. bool fullpath = false;
  313. Assembly assembly = null;
  314. try {
  315. assembly = Assembly.LoadWithPartialName (name);
  316. string loc = assembly.Location;
  317. fullpath = (Path.GetDirectoryName (loc) == PrivateBinPath);
  318. } catch (Exception e) {
  319. ThrowParseException ("Assembly " + name + " not found", e);
  320. }
  321. AddAssembly (assembly, fullpath);
  322. return assembly;
  323. }
  324. internal virtual void ProcessMainAttributes (Hashtable atts)
  325. {
  326. atts.Remove ("Description"); // ignored
  327. atts.Remove ("CodeBehind"); // ignored
  328. atts.Remove ("AspCompat"); // ignored
  329. debug = GetBool (atts, "Debug", true);
  330. compilerOptions = GetString (atts, "CompilerOptions", "");
  331. language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
  332. string src = GetString (atts, "Src", null);
  333. if (src != null)
  334. srcAssembly = GetAssemblyFromSource (src);
  335. string inherits = GetString (atts, "Inherits", null);
  336. if (inherits != null)
  337. SetBaseType (inherits);
  338. className = GetString (atts, "ClassName", null);
  339. if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
  340. ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
  341. if (atts.Count > 0)
  342. ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
  343. }
  344. internal void SetBaseType (string type)
  345. {
  346. if (type == DefaultBaseTypeName)
  347. return;
  348. Type parent = null;
  349. if (srcAssembly != null)
  350. parent = srcAssembly.GetType (type);
  351. if (parent == null)
  352. parent = LoadType (type);
  353. if (parent == null)
  354. ThrowParseException ("Cannot find type " + type);
  355. if (!DefaultBaseType.IsAssignableFrom (parent))
  356. ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
  357. baseType = parent;
  358. }
  359. Assembly GetAssemblyFromSource (string vpath)
  360. {
  361. vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
  362. string realPath = MapPath (vpath, false);
  363. if (!File.Exists (realPath))
  364. ThrowParseException ("File " + vpath + " not found");
  365. AddDependency (realPath);
  366. CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
  367. if (result.NativeCompilerReturnValue != 0) {
  368. StreamReader reader = new StreamReader (realPath);
  369. throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
  370. }
  371. AddAssembly (result.CompiledAssembly, true);
  372. return result.CompiledAssembly;
  373. }
  374. internal abstract Type DefaultBaseType { get; }
  375. internal abstract string DefaultBaseTypeName { get; }
  376. internal abstract string DefaultDirectiveName { get; }
  377. internal string InputFile
  378. {
  379. get { return inputFile; }
  380. set { inputFile = value; }
  381. }
  382. internal string Text
  383. {
  384. get { return text; }
  385. set { text = value; }
  386. }
  387. internal Type BaseType
  388. {
  389. get {
  390. if (baseType == null)
  391. baseType = DefaultBaseType;
  392. return baseType;
  393. }
  394. }
  395. internal string ClassName {
  396. get {
  397. if (className != null)
  398. return className;
  399. className = Path.GetFileName (inputFile).Replace ('.', '_');
  400. className = className.Replace ('-', '_');
  401. className = className.Replace (' ', '_');
  402. if (Char.IsDigit(className[0])) {
  403. className = "_" + className;
  404. }
  405. return className;
  406. }
  407. }
  408. internal string PrivateBinPath {
  409. get {
  410. if (privateBinPath != null)
  411. return privateBinPath;
  412. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  413. privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
  414. return privateBinPath;
  415. }
  416. }
  417. internal ArrayList Scripts {
  418. get {
  419. if (scripts == null)
  420. scripts = new ArrayList ();
  421. return scripts;
  422. }
  423. }
  424. internal ArrayList Imports {
  425. get { return imports; }
  426. }
  427. internal ArrayList Assemblies {
  428. get {
  429. if (appAssemblyIndex != -1) {
  430. object o = assemblies [appAssemblyIndex];
  431. assemblies.RemoveAt (appAssemblyIndex);
  432. assemblies.Add (o);
  433. appAssemblyIndex = -1;
  434. }
  435. return assemblies;
  436. }
  437. }
  438. internal ArrayList Interfaces {
  439. get { return interfaces; }
  440. }
  441. internal RootBuilder RootBuilder {
  442. get { return rootBuilder; }
  443. set { rootBuilder = value; }
  444. }
  445. internal ArrayList Dependencies {
  446. get { return dependencies; }
  447. }
  448. internal string CompilerOptions {
  449. get { return compilerOptions; }
  450. }
  451. internal string Language {
  452. get { return language; }
  453. }
  454. internal bool Debug {
  455. get { return debug; }
  456. }
  457. internal bool OutputCache {
  458. get { return output_cache; }
  459. }
  460. internal int OutputCacheDuration {
  461. get { return oc_duration; }
  462. }
  463. internal string OutputCacheVaryByHeader {
  464. get { return oc_header; }
  465. }
  466. internal string OutputCacheVaryByCustom {
  467. get { return oc_custom; }
  468. }
  469. internal string OutputCacheVaryByControls {
  470. get { return oc_controls; }
  471. }
  472. internal bool OutputCacheShared {
  473. get { return oc_shared; }
  474. }
  475. internal OutputCacheLocation OutputCacheLocation {
  476. get { return oc_location; }
  477. }
  478. internal string OutputCacheVaryByParam {
  479. get { return oc_param; }
  480. }
  481. internal PagesConfiguration PagesConfig {
  482. get { return PagesConfiguration.GetInstance (Context); }
  483. }
  484. }
  485. }