TemplateParser.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. //
  2. // System.Web.UI.TemplateParser
  3. //
  4. // Authors:
  5. // Duncan Mak ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Marek Habersack ([email protected])
  8. //
  9. // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
  10. // Copyright (C) 2005-2008 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.CodeDom.Compiler;
  32. using System.Collections;
  33. using System.ComponentModel;
  34. using System.Globalization;
  35. using System.IO;
  36. using System.Reflection;
  37. using System.Security.Permissions;
  38. using System.Text;
  39. using System.Threading;
  40. using System.Web.Compilation;
  41. using System.Web.Configuration;
  42. using System.Web.Hosting;
  43. using System.Web.Util;
  44. #if NET_2_0
  45. using System.Collections.Generic;
  46. #endif
  47. namespace System.Web.UI {
  48. internal class ServerSideScript
  49. {
  50. public readonly string Script;
  51. public readonly ILocation Location;
  52. public ServerSideScript (string script, ILocation location)
  53. {
  54. Script = script;
  55. Location = location;
  56. }
  57. }
  58. // CAS
  59. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  60. [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  61. public abstract class TemplateParser : BaseParser
  62. {
  63. string inputFile;
  64. string text;
  65. Hashtable mainAttributes;
  66. ArrayList dependencies;
  67. ArrayList assemblies;
  68. Hashtable anames;
  69. ArrayList imports;
  70. ArrayList interfaces;
  71. ArrayList scripts;
  72. Type baseType;
  73. bool baseTypeIsGlobal = true;
  74. string className;
  75. RootBuilder rootBuilder;
  76. bool debug;
  77. string compilerOptions;
  78. string language;
  79. bool implicitLanguage;
  80. bool strictOn ;
  81. bool explicitOn;
  82. bool linePragmasOn = true;
  83. bool output_cache;
  84. int oc_duration;
  85. string oc_header, oc_custom, oc_param, oc_controls;
  86. #if NET_2_0
  87. string oc_content_encodings;
  88. #endif
  89. bool oc_shared;
  90. OutputCacheLocation oc_location;
  91. CultureInfo invariantCulture = CultureInfo.InvariantCulture;
  92. #if NET_2_0
  93. byte[] md5checksum;
  94. string src;
  95. bool srcIsLegacy;
  96. string partialClassName;
  97. string codeFileBaseClass;
  98. string metaResourceKey;
  99. Type codeFileBaseClassType;
  100. string pageParserFilterTypeName;
  101. Type pageParserFilterType;
  102. PageParserFilter pageParserFilter;
  103. List <UnknownAttributeDescriptor> unknownMainAttributes;
  104. Stack <string> includeDirs;
  105. List <string> registeredTagNames;
  106. #else
  107. Stack includeDirs;
  108. Assembly srcAssembly;
  109. #endif
  110. ILocation directiveLocation;
  111. int appAssemblyIndex = -1;
  112. internal TemplateParser ()
  113. {
  114. LoadConfigDefaults ();
  115. imports = new ArrayList ();
  116. #if NET_2_0
  117. AddNamespaces (imports);
  118. #else
  119. imports.Add ("System");
  120. imports.Add ("System.Collections");
  121. imports.Add ("System.Collections.Specialized");
  122. imports.Add ("System.Configuration");
  123. imports.Add ("System.Text");
  124. imports.Add ("System.Text.RegularExpressions");
  125. imports.Add ("System.Web");
  126. imports.Add ("System.Web.Caching");
  127. imports.Add ("System.Web.Security");
  128. imports.Add ("System.Web.SessionState");
  129. imports.Add ("System.Web.UI");
  130. imports.Add ("System.Web.UI.WebControls");
  131. imports.Add ("System.Web.UI.HtmlControls");
  132. #endif
  133. assemblies = new ArrayList ();
  134. #if NET_2_0
  135. CompilationSection compConfig = CompilationConfig;
  136. bool addAssembliesInBin = false;
  137. foreach (AssemblyInfo info in compConfig.Assemblies) {
  138. if (info.Assembly == "*")
  139. addAssembliesInBin = true;
  140. else
  141. AddAssemblyByName (info.Assembly);
  142. }
  143. if (addAssembliesInBin)
  144. AddAssembliesInBin ();
  145. foreach (NamespaceInfo info in PagesConfig.Namespaces) {
  146. imports.Add (info.Namespace);
  147. }
  148. #else
  149. CompilationConfiguration compConfig = CompilationConfig;
  150. foreach (string a in compConfig.Assemblies)
  151. AddAssemblyByName (a);
  152. if (compConfig.AssembliesInBin)
  153. AddAssembliesInBin ();
  154. #endif
  155. language = compConfig.DefaultLanguage;
  156. implicitLanguage = true;
  157. }
  158. internal virtual void LoadConfigDefaults ()
  159. {
  160. debug = CompilationConfig.Debug;
  161. #if NET_2_0
  162. pageParserFilterTypeName = PagesConfig.PageParserFilterType;
  163. #endif
  164. }
  165. internal void AddApplicationAssembly ()
  166. {
  167. if (Context.ApplicationInstance == null)
  168. return; // this may happen if we have Global.asax and have
  169. // controls registered from Web.Config
  170. string location = Context.ApplicationInstance.AssemblyLocation;
  171. if (location != typeof (TemplateParser).Assembly.Location) {
  172. appAssemblyIndex = assemblies.Add (location);
  173. }
  174. }
  175. protected abstract Type CompileIntoType ();
  176. #if NET_2_0
  177. internal void AddControl (Type type, IDictionary attributes)
  178. {
  179. AspGenerator generator = AspGenerator;
  180. if (generator == null)
  181. return;
  182. generator.AddControl (type, attributes);
  183. }
  184. void AddNamespaces (ArrayList imports)
  185. {
  186. if (BuildManager.HaveResources)
  187. imports.Add ("System.Resources");
  188. PagesSection pages = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
  189. if (pages == null)
  190. return;
  191. NamespaceCollection namespaces = pages.Namespaces;
  192. if (namespaces == null || namespaces.Count == 0)
  193. return;
  194. foreach (NamespaceInfo nsi in namespaces)
  195. imports.Add (nsi.Namespace);
  196. }
  197. #endif
  198. internal void RegisterCustomControl (string tagPrefix, string tagName, string src)
  199. {
  200. string realpath = null;
  201. bool fileExists = false;
  202. #if NET_2_0
  203. VirtualFile vf = null;
  204. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  205. VirtualPath vp = new VirtualPath (src, BaseVirtualDir);
  206. string vpAbsolute = vp.Absolute;
  207. if (vpp.FileExists (vpAbsolute)) {
  208. fileExists = true;
  209. vf = vpp.GetFile (vpAbsolute);
  210. if (vf != null)
  211. realpath = MapPath (vf.VirtualPath);
  212. }
  213. #else
  214. realpath = MapPath (src);
  215. fileExists = File.Exists (realpath);
  216. #endif
  217. if (!fileExists)
  218. ThrowParseFileNotFound (src);
  219. if (String.Compare (realpath, inputFile, false, invariantCulture) == 0)
  220. return;
  221. #if NET_2_0
  222. string vpath = vf.VirtualPath;
  223. #else
  224. string vpath = VirtualPathUtility.Combine (BaseVirtualDir, src);
  225. if (VirtualPathUtility.IsAbsolute (vpath))
  226. vpath = VirtualPathUtility.ToAppRelative (vpath);
  227. #endif
  228. try {
  229. #if NET_2_0
  230. RegisterTagName (tagPrefix + ":" + tagName);
  231. RootBuilder.Foundry.RegisterFoundry (tagPrefix, tagName, vpath);
  232. #else
  233. Type type = null;
  234. ArrayList other_deps = new ArrayList ();
  235. type = UserControlParser.GetCompiledType (vpath, realpath, other_deps, Context);
  236. foreach (string s in other_deps)
  237. AddDependency (s);
  238. AddAssembly (type.Assembly, true);
  239. RootBuilder.Foundry.RegisterFoundry (tagPrefix, tagName, type);
  240. #endif
  241. AddDependency (vpath);
  242. } catch (ParseException pe) {
  243. if (this is UserControlParser)
  244. throw new ParseException (Location, pe.Message, pe);
  245. throw;
  246. }
  247. }
  248. internal void RegisterNamespace (string tagPrefix, string ns, string assembly)
  249. {
  250. AddImport (ns);
  251. Assembly ass = null;
  252. if (assembly != null && assembly.Length > 0)
  253. ass = AddAssemblyByName (assembly);
  254. RootBuilder.Foundry.RegisterFoundry (tagPrefix, ass, ns);
  255. }
  256. internal virtual void HandleOptions (object obj)
  257. {
  258. }
  259. internal static string GetOneKey (Hashtable tbl)
  260. {
  261. foreach (object key in tbl.Keys)
  262. return key.ToString ();
  263. return null;
  264. }
  265. internal virtual void AddDirective (string directive, Hashtable atts)
  266. {
  267. #if NET_2_0
  268. var pageParserFilter = PageParserFilter;
  269. if (pageParserFilter != null)
  270. pageParserFilter.PreprocessDirective (directive.ToLower (CultureInfo.InvariantCulture), atts);
  271. #endif
  272. if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
  273. if (mainAttributes != null)
  274. ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
  275. mainAttributes = atts;
  276. ProcessMainAttributes (mainAttributes);
  277. return;
  278. }
  279. int cmp = String.Compare ("Assembly", directive, true);
  280. if (cmp == 0) {
  281. string name = GetString (atts, "Name", null);
  282. string src = GetString (atts, "Src", null);
  283. if (atts.Count > 0)
  284. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  285. if (name == null && src == null)
  286. ThrowParseException ("You gotta specify Src or Name");
  287. if (name != null && src != null)
  288. ThrowParseException ("Src and Name cannot be used together");
  289. if (name != null) {
  290. AddAssemblyByName (name);
  291. } else {
  292. GetAssemblyFromSource (src);
  293. }
  294. return;
  295. }
  296. cmp = String.Compare ("Import", directive, true);
  297. if (cmp == 0) {
  298. string namesp = GetString (atts, "Namespace", null);
  299. if (atts.Count > 0)
  300. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  301. if (namesp != null && namesp != "")
  302. AddImport (namesp);
  303. return;
  304. }
  305. cmp = String.Compare ("Implements", directive, true);
  306. if (cmp == 0) {
  307. string ifacename = GetString (atts, "Interface", "");
  308. if (atts.Count > 0)
  309. ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
  310. Type iface = LoadType (ifacename);
  311. if (iface == null)
  312. ThrowParseException ("Cannot find type " + ifacename);
  313. if (!iface.IsInterface)
  314. ThrowParseException (iface + " is not an interface");
  315. AddInterface (iface.FullName);
  316. return;
  317. }
  318. cmp = String.Compare ("OutputCache", directive, true);
  319. if (cmp == 0) {
  320. HttpResponse response = HttpContext.Current.Response;
  321. if (response != null)
  322. response.Cache.SetValidUntilExpires (true);
  323. output_cache = true;
  324. if (atts ["Duration"] == null)
  325. ThrowParseException ("The directive is missing a 'duration' attribute.");
  326. if (atts ["VaryByParam"] == null && atts ["VaryByControl"] == null)
  327. ThrowParseException ("This directive is missing 'VaryByParam' " +
  328. "or 'VaryByControl' attribute, which should be set to \"none\", \"*\", " +
  329. "or a list of name/value pairs.");
  330. foreach (DictionaryEntry entry in atts) {
  331. string key = (string) entry.Key;
  332. switch (key.ToLower ()) {
  333. case "duration":
  334. oc_duration = Int32.Parse ((string) entry.Value);
  335. if (oc_duration < 1)
  336. ThrowParseException ("The 'duration' attribute must be set " +
  337. "to a positive integer value");
  338. break;
  339. #if NET_2_0
  340. case "varybycontentencodings":
  341. oc_content_encodings = (string) entry.Value;
  342. break;
  343. #endif
  344. case "varybyparam":
  345. oc_param = (string) entry.Value;
  346. if (String.Compare (oc_param, "none") == 0)
  347. oc_param = null;
  348. break;
  349. case "varybyheader":
  350. oc_header = (string) entry.Value;
  351. break;
  352. case "varybycustom":
  353. oc_custom = (string) entry.Value;
  354. break;
  355. case "location":
  356. if (!(this is PageParser))
  357. goto default;
  358. try {
  359. oc_location = (OutputCacheLocation) Enum.Parse (
  360. typeof (OutputCacheLocation), (string) entry.Value, true);
  361. } catch {
  362. ThrowParseException ("The 'location' attribute is case sensitive and " +
  363. "must be one of the following values: Any, Client, " +
  364. "Downstream, Server, None, ServerAndClient.");
  365. }
  366. break;
  367. case "varybycontrol":
  368. #if ONLY_1_1
  369. if (this is PageParser)
  370. goto default;
  371. #endif
  372. oc_controls = (string) entry.Value;
  373. break;
  374. case "shared":
  375. if (this is PageParser)
  376. goto default;
  377. try {
  378. oc_shared = Boolean.Parse ((string) entry.Value);
  379. } catch {
  380. ThrowParseException ("The 'shared' attribute is case sensitive" +
  381. " and must be set to 'true' or 'false'.");
  382. }
  383. break;
  384. default:
  385. ThrowParseException ("The '" + key + "' attribute is not " +
  386. "supported by the 'Outputcache' directive.");
  387. break;
  388. }
  389. }
  390. return;
  391. }
  392. ThrowParseException ("Unknown directive: " + directive);
  393. }
  394. internal Type LoadType (string typeName)
  395. {
  396. Type type = HttpApplication.LoadType (typeName);
  397. if (type == null)
  398. return null;
  399. Assembly asm = type.Assembly;
  400. string location = asm.Location;
  401. string dirname = Path.GetDirectoryName (location);
  402. bool doAddAssembly = true;
  403. if (dirname == HttpApplication.BinDirectory)
  404. doAddAssembly = false;
  405. if (doAddAssembly)
  406. AddAssembly (asm, true);
  407. return type;
  408. }
  409. void AddAssembliesInBin ()
  410. {
  411. foreach (string s in HttpApplication.BinDirectoryAssemblies)
  412. assemblies.Add (s);
  413. }
  414. internal virtual void AddInterface (string iface)
  415. {
  416. if (interfaces == null)
  417. interfaces = new ArrayList ();
  418. if (!interfaces.Contains (iface))
  419. interfaces.Add (iface);
  420. }
  421. internal virtual void AddImport (string namesp)
  422. {
  423. if (imports == null)
  424. imports = new ArrayList ();
  425. if (!imports.Contains (namesp))
  426. imports.Add (namesp);
  427. }
  428. internal virtual void AddSourceDependency (string filename)
  429. {
  430. if (dependencies != null && dependencies.Contains (filename))
  431. ThrowParseException ("Circular file references are not allowed. File: " + filename);
  432. AddDependency (filename);
  433. }
  434. internal virtual void AddDependency (string filename)
  435. {
  436. if (filename == null || filename == String.Empty)
  437. return;
  438. if (dependencies == null)
  439. dependencies = new ArrayList ();
  440. if (!dependencies.Contains (filename))
  441. dependencies.Add (filename);
  442. }
  443. internal virtual void AddAssembly (Assembly assembly, bool fullPath)
  444. {
  445. if (assembly == null || assembly.Location == String.Empty)
  446. return;
  447. if (anames == null)
  448. anames = new Hashtable ();
  449. string name = assembly.GetName ().Name;
  450. string loc = assembly.Location;
  451. if (fullPath) {
  452. if (!assemblies.Contains (loc)) {
  453. assemblies.Add (loc);
  454. }
  455. anames [name] = loc;
  456. anames [loc] = assembly;
  457. } else {
  458. if (!assemblies.Contains (name)) {
  459. assemblies.Add (name);
  460. }
  461. anames [name] = assembly;
  462. }
  463. }
  464. internal virtual Assembly AddAssemblyByFileName (string filename)
  465. {
  466. Assembly assembly = null;
  467. Exception error = null;
  468. try {
  469. assembly = Assembly.LoadFrom (filename);
  470. } catch (Exception e) { error = e; }
  471. if (assembly == null)
  472. ThrowParseException ("Assembly " + filename + " not found", error);
  473. AddAssembly (assembly, true);
  474. return assembly;
  475. }
  476. internal virtual Assembly AddAssemblyByName (string name)
  477. {
  478. if (anames == null)
  479. anames = new Hashtable ();
  480. if (anames.Contains (name)) {
  481. object o = anames [name];
  482. if (o is string)
  483. o = anames [o];
  484. return (Assembly) o;
  485. }
  486. Assembly assembly = null;
  487. Exception error = null;
  488. try {
  489. assembly = Assembly.Load (name);
  490. } catch (Exception e) { error = e; }
  491. if (assembly == null) {
  492. try {
  493. assembly = Assembly.LoadWithPartialName (name);
  494. } catch (Exception e) { error = e; }
  495. }
  496. if (assembly == null)
  497. ThrowParseException ("Assembly " + name + " not found", error);
  498. AddAssembly (assembly, true);
  499. return assembly;
  500. }
  501. internal virtual void ProcessMainAttributes (Hashtable atts)
  502. {
  503. directiveLocation = new System.Web.Compilation.Location (Location);
  504. #if NET_2_0
  505. CompilationSection compConfig;
  506. #else
  507. CompilationConfiguration compConfig;
  508. #endif
  509. compConfig = CompilationConfig;
  510. atts.Remove ("Description"); // ignored
  511. #if NET_1_1
  512. atts.Remove ("CodeBehind"); // ignored
  513. #endif
  514. atts.Remove ("AspCompat"); // ignored
  515. debug = GetBool (atts, "Debug", compConfig.Debug);
  516. compilerOptions = GetString (atts, "CompilerOptions", "");
  517. language = GetString (atts, "Language", "");
  518. if (language.Length != 0)
  519. implicitLanguage = false;
  520. else
  521. language = compConfig.DefaultLanguage;
  522. strictOn = GetBool (atts, "Strict", compConfig.Strict);
  523. explicitOn = GetBool (atts, "Explicit", compConfig.Explicit);
  524. if (atts.ContainsKey ("LinePragmas"))
  525. linePragmasOn = GetBool (atts, "LinePragmas", true);
  526. string inherits = GetString (atts, "Inherits", null);
  527. #if NET_2_0
  528. string srcRealPath = null;
  529. // In ASP 2, the source file is actually integrated with
  530. // the generated file via the use of partial classes. This
  531. // means that the code file has to be confirmed, but not
  532. // used at this point.
  533. src = GetString (atts, "CodeFile", null);
  534. codeFileBaseClass = GetString (atts, "CodeFileBaseClass", null);
  535. if (src == null && codeFileBaseClass != null)
  536. ThrowParseException ("The 'CodeFileBaseClass' attribute cannot be used without a 'CodeFile' attribute");
  537. string legacySrc = GetString (atts, "Src", null);
  538. if (legacySrc != null) {
  539. legacySrc = UrlUtils.Combine (BaseVirtualDir, legacySrc);
  540. GetAssemblyFromSource (legacySrc);
  541. if (src == null) {
  542. src = legacySrc;
  543. legacySrc = MapPath (legacySrc, false);
  544. srcRealPath = legacySrc;
  545. if (!File.Exists (srcRealPath))
  546. ThrowParseException ("File " + src + " not found");
  547. srcIsLegacy = true;
  548. } else
  549. legacySrc = MapPath (legacySrc, false);
  550. AddDependency (legacySrc);
  551. }
  552. if (!srcIsLegacy && src != null && inherits != null) {
  553. // Make sure the source exists
  554. src = UrlUtils.Combine (BaseVirtualDir, src);
  555. srcRealPath = MapPath (src, false);
  556. if (!HostingEnvironment.VirtualPathProvider.FileExists (src))
  557. ThrowParseException ("File " + src + " not found");
  558. // We are going to create a partial class that shares
  559. // the same name as the inherits tag, so reset the
  560. // name. The base type is changed because it is the
  561. // code file's responsibilty to extend the classes
  562. // needed.
  563. partialClassName = inherits;
  564. // Add the code file as an option to the
  565. // compiler. This lets both files be compiled at once.
  566. compilerOptions += " \"" + srcRealPath + "\"";
  567. if (codeFileBaseClass != null) {
  568. try {
  569. codeFileBaseClassType = LoadType (codeFileBaseClass);
  570. } catch (Exception) {
  571. }
  572. if (codeFileBaseClassType == null)
  573. ThrowParseException ("Could not load type '{0}'", codeFileBaseClass);
  574. }
  575. } else if (inherits != null) {
  576. // We just set the inherits directly because this is a
  577. // Single-Page model.
  578. SetBaseType (inherits);
  579. }
  580. #else
  581. string src = GetString (atts, "Src", null);
  582. if (src != null)
  583. srcAssembly = GetAssemblyFromSource (src);
  584. if (inherits != null)
  585. SetBaseType (inherits);
  586. #endif
  587. if (src != null) {
  588. if (VirtualPathUtility.IsAbsolute (src))
  589. src = VirtualPathUtility.ToAppRelative (src);
  590. AddDependency (src);
  591. }
  592. className = GetString (atts, "ClassName", null);
  593. if (className != null) {
  594. #if NET_2_0
  595. string [] identifiers = className.Split ('.');
  596. for (int i = 0; i < identifiers.Length; i++)
  597. if (!CodeGenerator.IsValidLanguageIndependentIdentifier (identifiers [i]))
  598. ThrowParseException (String.Format ("'{0}' is not a valid "
  599. + "value for attribute 'classname'.", className));
  600. #else
  601. if (!CodeGenerator.IsValidLanguageIndependentIdentifier (className))
  602. ThrowParseException (String.Format ("'{0}' is not a valid "
  603. + "value for attribute 'classname'.", className));
  604. #endif
  605. }
  606. #if NET_2_0
  607. if (this is TemplateControlParser)
  608. metaResourceKey = GetString (atts, "meta:resourcekey", null);
  609. if (inherits != null && (this is PageParser || this is UserControlParser) && atts.Count > 0) {
  610. if (unknownMainAttributes == null)
  611. unknownMainAttributes = new List <UnknownAttributeDescriptor> ();
  612. string key, val;
  613. foreach (DictionaryEntry de in atts) {
  614. key = de.Key as string;
  615. val = de.Value as string;
  616. if (String.IsNullOrEmpty (key) || String.IsNullOrEmpty (val))
  617. continue;
  618. CheckUnknownAttribute (key, val, inherits);
  619. }
  620. return;
  621. }
  622. #endif
  623. if (atts.Count > 0)
  624. ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
  625. }
  626. #if NET_2_0
  627. void RegisterTagName (string tagName)
  628. {
  629. if (registeredTagNames == null)
  630. registeredTagNames = new List <string> ();
  631. if (registeredTagNames.Contains (tagName))
  632. return;
  633. registeredTagNames.Add (tagName);
  634. }
  635. void CheckUnknownAttribute (string name, string val, string inherits)
  636. {
  637. MemberInfo mi = null;
  638. bool missing = false;
  639. string memberName = name.Trim ().ToLower (CultureInfo.InvariantCulture);
  640. Type parent = codeFileBaseClassType;
  641. if (parent == null)
  642. parent = baseType;
  643. try {
  644. MemberInfo[] infos = parent.GetMember (memberName,
  645. MemberTypes.Field | MemberTypes.Property,
  646. BindingFlags.Public | BindingFlags.Instance |
  647. BindingFlags.IgnoreCase | BindingFlags.Static);
  648. if (infos.Length != 0) {
  649. // prefer public properties to public methods (it's what MS.NET does)
  650. foreach (MemberInfo tmp in infos) {
  651. if (tmp is PropertyInfo) {
  652. mi = tmp;
  653. break;
  654. }
  655. }
  656. if (mi == null)
  657. mi = infos [0];
  658. } else
  659. missing = true;
  660. } catch (Exception) {
  661. missing = true;
  662. }
  663. if (missing)
  664. ThrowParseException (
  665. "Error parsing attribute '{0}': Type '{1}' does not have a public property named '{0}'",
  666. memberName, inherits);
  667. Type memberType = null;
  668. if (mi is PropertyInfo) {
  669. PropertyInfo pi = mi as PropertyInfo;
  670. if (!pi.CanWrite)
  671. ThrowParseException (
  672. "Error parsing attribute '{0}': The '{0}' property is read-only and cannot be set.",
  673. memberName);
  674. memberType = pi.PropertyType;
  675. } else if (mi is FieldInfo) {
  676. memberType = ((FieldInfo)mi).FieldType;
  677. } else
  678. ThrowParseException ("Could not determine member the kind of '{0}' in base type '{1}",
  679. memberName, inherits);
  680. TypeConverter converter = TypeDescriptor.GetConverter (memberType);
  681. bool convertible = true;
  682. object value = null;
  683. if (converter == null || !converter.CanConvertFrom (typeof (string)))
  684. convertible = false;
  685. if (convertible) {
  686. try {
  687. value = converter.ConvertFromInvariantString (val);
  688. } catch (Exception) {
  689. convertible = false;
  690. }
  691. }
  692. if (!convertible)
  693. ThrowParseException ("Error parsing attribute '{0}': Cannot create an object of type '{1}' from its string representation '{2}' for the '{3}' property.",
  694. memberName, memberType, val, mi.Name);
  695. UnknownAttributeDescriptor desc = new UnknownAttributeDescriptor (mi, value);
  696. unknownMainAttributes.Add (desc);
  697. }
  698. #endif
  699. internal void SetBaseType (string type)
  700. {
  701. Type parent;
  702. if (type == null || type == DefaultBaseTypeName)
  703. parent = DefaultBaseType;
  704. else
  705. parent = null;
  706. if (parent == null) {
  707. #if NET_2_0
  708. parent = LoadType (type);
  709. #else
  710. parent = null;
  711. if (srcAssembly != null)
  712. parent = srcAssembly.GetType (type);
  713. if (parent == null)
  714. parent = LoadType (type);
  715. #endif
  716. if (parent == null)
  717. ThrowParseException ("Cannot find type " + type);
  718. if (!DefaultBaseType.IsAssignableFrom (parent))
  719. ThrowParseException ("The parent type '" + type + "' does not derive from " + DefaultBaseType);
  720. }
  721. #if NET_2_0
  722. var pageParserFilter = PageParserFilter;
  723. if (pageParserFilter != null && !pageParserFilter.AllowBaseType (parent))
  724. throw new HttpException ("Base type '" + parent + "' is not allowed.");
  725. #endif
  726. baseType = parent;
  727. }
  728. internal void SetLanguage (string language)
  729. {
  730. this.language = language;
  731. implicitLanguage = false;
  732. }
  733. internal void PushIncludeDir (string dir)
  734. {
  735. if (includeDirs == null) {
  736. #if NET_2_0
  737. includeDirs = new Stack <string> (1);
  738. #else
  739. includeDirs = new Stack (1);
  740. #endif
  741. }
  742. includeDirs.Push (dir);
  743. }
  744. internal string PopIncludeDir ()
  745. {
  746. if (includeDirs == null || includeDirs.Count == 0)
  747. return null;
  748. return includeDirs.Pop () as string;
  749. }
  750. Assembly GetAssemblyFromSource (string vpath)
  751. {
  752. vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
  753. string realPath = MapPath (vpath, false);
  754. if (!File.Exists (realPath))
  755. ThrowParseException ("File " + vpath + " not found");
  756. AddSourceDependency (vpath);
  757. CompilerResults result;
  758. #if NET_2_0
  759. string tmp;
  760. CompilerParameters parameters;
  761. CodeDomProvider provider = BaseCompiler.CreateProvider (HttpContext.Current, language, out parameters, out tmp);
  762. if (provider == null)
  763. throw new HttpException ("Cannot find provider for language '" + language + "'.");
  764. AssemblyBuilder abuilder = new AssemblyBuilder (provider);
  765. abuilder.CompilerOptions = parameters;
  766. abuilder.AddAssemblyReference (BuildManager.GetReferencedAssemblies () as List <Assembly>);
  767. abuilder.AddCodeFile (realPath);
  768. result = abuilder.BuildAssembly (new VirtualPath (vpath));
  769. #else
  770. result = CachingCompiler.Compile (language, realPath, realPath, assemblies, Debug);
  771. #endif
  772. if (result.NativeCompilerReturnValue != 0) {
  773. using (StreamReader reader = new StreamReader (realPath)) {
  774. throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
  775. }
  776. }
  777. AddAssembly (result.CompiledAssembly, true);
  778. return result.CompiledAssembly;
  779. }
  780. internal abstract string DefaultBaseTypeName { get; }
  781. internal abstract string DefaultDirectiveName { get; }
  782. internal bool LinePragmasOn {
  783. get { return linePragmasOn; }
  784. }
  785. #if NET_2_0
  786. internal byte[] MD5Checksum {
  787. get { return md5checksum; }
  788. set { md5checksum = value; }
  789. }
  790. internal string PageParserFilterTypeName {
  791. get { return pageParserFilterTypeName; }
  792. }
  793. internal PageParserFilter PageParserFilter {
  794. get {
  795. if (pageParserFilter != null)
  796. return pageParserFilter;
  797. if (String.IsNullOrEmpty (pageParserFilterTypeName))
  798. return null;
  799. pageParserFilter = Activator.CreateInstance (PageParserFilterType) as PageParserFilter;
  800. pageParserFilter.Initialize (VirtualPath, this);
  801. return pageParserFilter;
  802. }
  803. }
  804. internal Type PageParserFilterType {
  805. get {
  806. if (pageParserFilterType == null)
  807. pageParserFilterType = Type.GetType (PageParserFilterTypeName, true);
  808. return pageParserFilterType;
  809. }
  810. }
  811. #endif
  812. internal Type DefaultBaseType {
  813. get {
  814. Type type = Type.GetType (DefaultBaseTypeName, true);
  815. return type;
  816. }
  817. }
  818. internal ILocation DirectiveLocation {
  819. get { return directiveLocation; }
  820. }
  821. #if NET_2_0
  822. internal VirtualPath VirtualPath {
  823. get;
  824. set;
  825. }
  826. #endif
  827. internal string ParserDir {
  828. get {
  829. if (includeDirs == null || includeDirs.Count == 0)
  830. return BaseDir;
  831. return includeDirs.Peek () as string;
  832. }
  833. }
  834. internal string InputFile
  835. {
  836. get { return inputFile; }
  837. set { inputFile = value; }
  838. }
  839. #if NET_2_0
  840. internal bool IsPartial {
  841. get { return (!srcIsLegacy && src != null); }
  842. }
  843. internal string CodeBehindSource {
  844. get {
  845. if (srcIsLegacy)
  846. return null;
  847. return src;
  848. }
  849. }
  850. internal string PartialClassName {
  851. get { return partialClassName; }
  852. }
  853. internal string CodeFileBaseClass {
  854. get { return codeFileBaseClass; }
  855. }
  856. internal string MetaResourceKey {
  857. get { return metaResourceKey; }
  858. }
  859. internal Type CodeFileBaseClassType
  860. {
  861. get { return codeFileBaseClassType; }
  862. }
  863. internal List <UnknownAttributeDescriptor> UnknownMainAttributes
  864. {
  865. get { return unknownMainAttributes; }
  866. }
  867. #endif
  868. internal string Text {
  869. get { return text; }
  870. set { text = value; }
  871. }
  872. internal Type BaseType {
  873. get {
  874. if (baseType == null)
  875. SetBaseType (DefaultBaseTypeName);
  876. return baseType;
  877. }
  878. }
  879. internal bool BaseTypeIsGlobal {
  880. get { return baseTypeIsGlobal; }
  881. set { baseTypeIsGlobal = value; }
  882. }
  883. #if NET_2_0
  884. static long autoClassCounter = 0;
  885. #endif
  886. internal string EncodeIdentifier (string value)
  887. {
  888. if (value == null || value.Length == 0 || CodeGenerator.IsValidLanguageIndependentIdentifier (value))
  889. return value;
  890. StringBuilder ret = new StringBuilder ();
  891. char ch = value [0];
  892. switch (Char.GetUnicodeCategory (ch)) {
  893. case UnicodeCategory.LetterNumber:
  894. case UnicodeCategory.LowercaseLetter:
  895. case UnicodeCategory.TitlecaseLetter:
  896. case UnicodeCategory.UppercaseLetter:
  897. case UnicodeCategory.OtherLetter:
  898. case UnicodeCategory.ModifierLetter:
  899. case UnicodeCategory.ConnectorPunctuation:
  900. ret.Append (ch);
  901. break;
  902. case UnicodeCategory.DecimalDigitNumber:
  903. ret.Append ('_');
  904. ret.Append (ch);
  905. break;
  906. default:
  907. ret.Append ('_');
  908. break;
  909. }
  910. for (int i = 1; i < value.Length; i++) {
  911. ch = value [i];
  912. switch (Char.GetUnicodeCategory (ch)) {
  913. case UnicodeCategory.LetterNumber:
  914. case UnicodeCategory.LowercaseLetter:
  915. case UnicodeCategory.TitlecaseLetter:
  916. case UnicodeCategory.UppercaseLetter:
  917. case UnicodeCategory.OtherLetter:
  918. case UnicodeCategory.ModifierLetter:
  919. case UnicodeCategory.ConnectorPunctuation:
  920. case UnicodeCategory.DecimalDigitNumber:
  921. case UnicodeCategory.NonSpacingMark:
  922. case UnicodeCategory.SpacingCombiningMark:
  923. case UnicodeCategory.Format:
  924. ret.Append (ch);
  925. break;
  926. default:
  927. ret.Append ('_');
  928. break;
  929. }
  930. }
  931. return ret.ToString ();
  932. }
  933. internal string ClassName {
  934. get {
  935. if (className != null)
  936. return className;
  937. #if NET_2_0
  938. string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
  939. string inFile;
  940. if (String.IsNullOrEmpty (inputFile)) {
  941. inFile = null;
  942. using (StreamReader sr = Reader as StreamReader) {
  943. if (sr != null) {
  944. FileStream fr = sr.BaseStream as FileStream;
  945. if (fr != null)
  946. inFile = fr.Name;
  947. }
  948. }
  949. } else
  950. inFile = inputFile;
  951. if (String.IsNullOrEmpty (inFile)) {
  952. // generate a unique class name
  953. long suffix;
  954. suffix = Interlocked.Increment (ref autoClassCounter);
  955. className = String.Format ("autoclass_nosource_{0:x}", suffix);
  956. return className;
  957. }
  958. if (StrUtils.StartsWith (inFile, physPath))
  959. className = inputFile.Substring (physPath.Length).ToLower (CultureInfo.InvariantCulture);
  960. else
  961. #endif
  962. className = Path.GetFileName (inputFile);
  963. className = EncodeIdentifier (className);
  964. return className;
  965. }
  966. }
  967. internal ArrayList Scripts {
  968. get {
  969. if (scripts == null)
  970. scripts = new ArrayList ();
  971. return scripts;
  972. }
  973. }
  974. internal ArrayList Imports {
  975. get { return imports; }
  976. }
  977. internal ArrayList Assemblies {
  978. get {
  979. if (appAssemblyIndex != -1) {
  980. object o = assemblies [appAssemblyIndex];
  981. assemblies.RemoveAt (appAssemblyIndex);
  982. assemblies.Add (o);
  983. appAssemblyIndex = -1;
  984. }
  985. return assemblies;
  986. }
  987. }
  988. internal ArrayList Interfaces {
  989. get { return interfaces; }
  990. }
  991. internal RootBuilder RootBuilder {
  992. get { return rootBuilder; }
  993. set { rootBuilder = value; }
  994. }
  995. internal ArrayList Dependencies {
  996. get { return dependencies; }
  997. set { dependencies = value; }
  998. }
  999. internal string CompilerOptions {
  1000. get { return compilerOptions; }
  1001. }
  1002. internal string Language {
  1003. get { return language; }
  1004. }
  1005. internal bool ImplicitLanguage {
  1006. get { return implicitLanguage; }
  1007. }
  1008. internal bool StrictOn {
  1009. get { return strictOn; }
  1010. }
  1011. internal bool ExplicitOn {
  1012. get { return explicitOn; }
  1013. }
  1014. internal bool Debug {
  1015. get { return debug; }
  1016. }
  1017. internal bool OutputCache {
  1018. get { return output_cache; }
  1019. }
  1020. internal int OutputCacheDuration {
  1021. get { return oc_duration; }
  1022. }
  1023. #if NET_2_0
  1024. internal string OutputCacheVaryByContentEncodings {
  1025. get { return oc_content_encodings; }
  1026. }
  1027. internal virtual TextReader Reader {
  1028. get { return null; }
  1029. set { /* no-op */ }
  1030. }
  1031. #endif
  1032. internal string OutputCacheVaryByHeader {
  1033. get { return oc_header; }
  1034. }
  1035. internal string OutputCacheVaryByCustom {
  1036. get { return oc_custom; }
  1037. }
  1038. internal string OutputCacheVaryByControls {
  1039. get { return oc_controls; }
  1040. }
  1041. internal bool OutputCacheShared {
  1042. get { return oc_shared; }
  1043. }
  1044. internal OutputCacheLocation OutputCacheLocation {
  1045. get { return oc_location; }
  1046. }
  1047. internal string OutputCacheVaryByParam {
  1048. get { return oc_param; }
  1049. }
  1050. #if NET_2_0
  1051. internal List <string> RegisteredTagNames {
  1052. get { return registeredTagNames; }
  1053. }
  1054. internal PagesSection PagesConfig {
  1055. get {
  1056. VirtualPath vp = VirtualPath;
  1057. string virtualPath = vp != null ? VirtualPath.Absolute : null;
  1058. if (!String.IsNullOrEmpty (virtualPath))
  1059. return WebConfigurationManager.GetSection ("system.web/pages", virtualPath) as PagesSection;
  1060. else
  1061. return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
  1062. }
  1063. }
  1064. internal AspGenerator AspGenerator {
  1065. get;
  1066. set;
  1067. }
  1068. #else
  1069. internal PagesConfiguration PagesConfig {
  1070. get { return PagesConfiguration.GetInstance (Context); }
  1071. }
  1072. #endif
  1073. }
  1074. }