TemplateParser.cs 15 KB

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