AspGenerator.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040
  1. //
  2. // System.Web.Compilation.AspGenerator
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.ComponentModel;
  12. using System.Drawing;
  13. using System.Diagnostics;
  14. using System.IO;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Web.UI;
  19. using System.Web.UI.HtmlControls;
  20. using System.Web.UI.WebControls;
  21. using System.Web.Util;
  22. namespace System.Web.Compilation
  23. {
  24. class ControlStack
  25. {
  26. private Stack controls;
  27. private ControlStackData top;
  28. private bool space_between_tags;
  29. private bool sbt_valid;
  30. class ControlStackData
  31. {
  32. public Type controlType;
  33. public string controlID;
  34. public string tagID;
  35. public ChildrenKind childKind;
  36. public string defaultPropertyName;
  37. public int childrenNumber;
  38. public Type container;
  39. public StringBuilder dataBindFunction;
  40. public StringBuilder codeRenderFunction;
  41. public bool useCodeRender;
  42. public int codeRenderIndex;
  43. public ControlStackData (Type controlType,
  44. string controlID,
  45. string tagID,
  46. ChildrenKind childKind,
  47. string defaultPropertyName,
  48. Type container)
  49. {
  50. this.controlType = controlType;
  51. this.controlID = controlID;
  52. this.tagID = tagID;
  53. this.childKind = childKind;
  54. this.defaultPropertyName = defaultPropertyName;
  55. this.container = container;
  56. childrenNumber = 0;
  57. }
  58. public override string ToString ()
  59. {
  60. return controlType + " " + controlID + " " + tagID + " " + childKind + " " + childrenNumber;
  61. }
  62. }
  63. public ControlStack ()
  64. {
  65. controls = new Stack ();
  66. }
  67. private Type GetContainerType (Type type)
  68. {
  69. if (type != typeof (System.Web.UI.Control) &&
  70. !type.IsSubclassOf (typeof (System.Web.UI.Control)))
  71. return null;
  72. Type container_type;
  73. if (type == typeof (System.Web.UI.WebControls.DataList))
  74. container_type = typeof (System.Web.UI.WebControls.DataListItem);
  75. else if (type == typeof (System.Web.UI.WebControls.DataGrid))
  76. container_type = typeof (System.Web.UI.WebControls.DataGridItem);
  77. else if (type == typeof (System.Web.UI.WebControls.Repeater))
  78. container_type = typeof (System.Web.UI.WebControls.RepeaterItem);
  79. else if (type == typeof (ListControl) || type.IsSubclassOf (typeof (ListControl)))
  80. container_type = type;
  81. else
  82. container_type = Container;
  83. return container_type;
  84. }
  85. public void Push (object o)
  86. {
  87. if (!(o is ControlStackData))
  88. return;
  89. controls.Push (o);
  90. top = (ControlStackData) o;
  91. sbt_valid = false;
  92. }
  93. public void Push (Type controlType,
  94. string controlID,
  95. string tagID,
  96. ChildrenKind childKind,
  97. string defaultPropertyName)
  98. {
  99. Type container_type = null;
  100. if (controlType != null){
  101. AddChild ();
  102. container_type = GetContainerType (controlType);
  103. if (container_type == null)
  104. container_type = this.Container;
  105. }
  106. top = new ControlStackData (controlType,
  107. controlID,
  108. tagID,
  109. childKind,
  110. defaultPropertyName,
  111. container_type);
  112. sbt_valid = false;
  113. controls.Push (top);
  114. }
  115. public object Pop ()
  116. {
  117. object item = controls.Pop ();
  118. if (controls.Count != 0)
  119. top = (ControlStackData) controls.Peek ();
  120. sbt_valid = false;
  121. return item;
  122. }
  123. public Type PeekType ()
  124. {
  125. return top.controlType;
  126. }
  127. public string PeekControlID ()
  128. {
  129. return top.controlID;
  130. }
  131. public string PeekTagID ()
  132. {
  133. return top.tagID;
  134. }
  135. public ChildrenKind PeekChildKind ()
  136. {
  137. return top.childKind;
  138. }
  139. public string PeekDefaultPropertyName ()
  140. {
  141. return top.defaultPropertyName;
  142. }
  143. public void AddChild ()
  144. {
  145. if (top != null)
  146. top.childrenNumber++;
  147. }
  148. public bool HasDataBindFunction ()
  149. {
  150. if (top.dataBindFunction == null || top.dataBindFunction.Length == 0)
  151. return false;
  152. return true;
  153. }
  154. public bool UseCodeRender
  155. {
  156. get {
  157. if (top.codeRenderFunction == null || top.codeRenderFunction.Length == 0)
  158. return false;
  159. return top.useCodeRender;
  160. }
  161. set { top.useCodeRender= value; }
  162. }
  163. public bool SpaceBetweenTags
  164. {
  165. get {
  166. if (!sbt_valid){
  167. sbt_valid = true;
  168. Type type = top.controlType;
  169. if (type.Namespace == "System.Web.UI.WebControls")
  170. space_between_tags = true;
  171. else if (type.IsSubclassOf (typeof (System.Web.UI.WebControls.WebControl)))
  172. space_between_tags = true;
  173. else if (type == typeof (System.Web.UI.HtmlControls.HtmlSelect))
  174. space_between_tags = true;
  175. else if (type == typeof (System.Web.UI.HtmlControls.HtmlTable))
  176. space_between_tags = true;
  177. else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableRow))
  178. space_between_tags = true;
  179. else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableCell))
  180. space_between_tags = true;
  181. else
  182. space_between_tags = false;
  183. }
  184. return space_between_tags;
  185. }
  186. }
  187. public Type Container {
  188. get {
  189. if (top == null)
  190. return null;
  191. return top.container;
  192. }
  193. }
  194. public StringBuilder DataBindFunction
  195. {
  196. get {
  197. if (top.dataBindFunction == null)
  198. top.dataBindFunction = new StringBuilder ();
  199. return top.dataBindFunction;
  200. }
  201. }
  202. public int CodeRenderIndex {
  203. get {
  204. return top.codeRenderIndex++;
  205. }
  206. }
  207. public StringBuilder CodeRenderFunction
  208. {
  209. get {
  210. if (top.codeRenderFunction == null)
  211. top.codeRenderFunction = new StringBuilder ();
  212. return top.codeRenderFunction;
  213. }
  214. }
  215. public int ChildIndex
  216. {
  217. get { return top.childrenNumber - 1; }
  218. }
  219. public int Count
  220. {
  221. get { return controls.Count; }
  222. }
  223. public override string ToString ()
  224. {
  225. return top.ToString () + " " + top.useCodeRender;
  226. }
  227. }
  228. enum ScriptStatus
  229. {
  230. Close,
  231. Open,
  232. Text
  233. }
  234. class AspGenerator
  235. {
  236. object [] parts;
  237. StringBuilder prolog;
  238. StringBuilder declarations;
  239. StringBuilder script;
  240. StringBuilder constructor;
  241. StringBuilder init_funcs;
  242. StringBuilder epilog;
  243. StringBuilder current_function;
  244. StringBuilder textChunk;
  245. Stack functions;
  246. ControlStack controls;
  247. bool parse_ok;
  248. bool has_form_tag;
  249. AspComponentFoundry aspFoundry;
  250. string classDecl;
  251. string className;
  252. string interfaces;
  253. string basetype;
  254. string parent;
  255. Type parentType;
  256. string fullPath;
  257. Hashtable options;
  258. string privateBinPath;
  259. string main_directive;
  260. static string app_file_wrong = "The content in the application file is not valid.";
  261. bool isPage;
  262. bool isUserControl;
  263. bool isApplication;
  264. Element current;
  265. ScriptStatus sstatus = ScriptStatus.Close;
  266. string waitClosing;
  267. HttpContext context;
  268. SessionState sessionState = SessionState.Enabled;
  269. static Type styleType = typeof (System.Web.UI.WebControls.Style);
  270. static Type fontinfoType = typeof (System.Web.UI.WebControls.FontInfo);
  271. enum UserControlResult
  272. {
  273. OK = 0,
  274. FileNotFound = 1,
  275. CompilationFailed = 2
  276. }
  277. enum SessionState
  278. {
  279. Enabled,
  280. ReadOnly,
  281. Disabled
  282. }
  283. public AspGenerator (string pathToFile)
  284. {
  285. if (pathToFile == null)
  286. throw new ArgumentNullException ("pathToFile");
  287. string filename = Path.GetFileName (pathToFile);
  288. this.className = filename.Replace ('.', '_'); // Overridden by @ Page classname
  289. this.className = className.Replace ('-', '_');
  290. this.className = className.Replace (' ', '_');
  291. Options ["ClassName"] = this.className;
  292. this.fullPath = Path.GetFullPath (pathToFile);
  293. this.has_form_tag = false;
  294. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  295. privateBinPath = setup.PrivateBinPath;
  296. // This is a hack until we can run stuff in different domains
  297. if (privateBinPath == null || privateBinPath.Length == 0)
  298. privateBinPath = "bin";
  299. if (!Path.IsPathRooted (privateBinPath)) {
  300. string appbase = setup.ApplicationBase;
  301. if (appbase.StartsWith ("file://"))
  302. appbase = appbase.Substring (7);
  303. privateBinPath = Path.Combine (appbase, privateBinPath);
  304. }
  305. Init ();
  306. }
  307. public string BaseType {
  308. get { return basetype; }
  309. set {
  310. if (parent == null)
  311. parent = value;
  312. basetype = value;
  313. isUserControl = (basetype == "System.Web.UI.UserControl");
  314. isPage = (basetype == "System.Web.UI.Page");
  315. isApplication = (basetype == "System.Web.HttpApplication");
  316. }
  317. }
  318. public bool IsUserControl {
  319. get { return isUserControl; }
  320. }
  321. public bool IsPage {
  322. get { return isPage; }
  323. }
  324. public bool IsApplication {
  325. get { return isApplication; }
  326. }
  327. public string Interfaces {
  328. get { return interfaces; }
  329. }
  330. public Hashtable Options {
  331. get {
  332. if (options == null)
  333. options = new Hashtable ();
  334. return options;
  335. }
  336. }
  337. internal HttpContext Context {
  338. get { return context; }
  339. set { context = value; }
  340. }
  341. bool AddUsing (string nspace)
  342. {
  343. string _using = "using " + nspace + ";";
  344. if (prolog.ToString ().IndexOf (_using) == -1) {
  345. prolog.AppendFormat ("\t{0}\n", _using);
  346. return true;
  347. }
  348. return false;
  349. }
  350. void AddInterface (Type type)
  351. {
  352. AddInterface (type.ToString ());
  353. }
  354. public void AddInterface (string iface)
  355. {
  356. if (interfaces == null) {
  357. interfaces = ", " + iface;
  358. } else {
  359. string s = ", " + iface;
  360. if (interfaces.IndexOf (s) == -1)
  361. interfaces += s;
  362. }
  363. }
  364. private AspComponentFoundry Foundry
  365. {
  366. get {
  367. if (aspFoundry == null)
  368. aspFoundry = new AspComponentFoundry ();
  369. return aspFoundry;
  370. }
  371. }
  372. private void Init ()
  373. {
  374. controls = new ControlStack ();
  375. controls.Push (typeof (System.Web.UI.Control), "Root", null, ChildrenKind.CONTROLS, null);
  376. prolog = new StringBuilder ();
  377. declarations = new StringBuilder ();
  378. script = new StringBuilder ();
  379. constructor = new StringBuilder ();
  380. init_funcs = new StringBuilder ();
  381. epilog = new StringBuilder ();
  382. textChunk = new StringBuilder ();
  383. current_function = new StringBuilder ();
  384. functions = new Stack ();
  385. functions.Push (current_function);
  386. parts = new Object [6];
  387. parts [0] = prolog;
  388. parts [1] = declarations;
  389. parts [2] = script;
  390. parts [3] = constructor;
  391. parts [4] = init_funcs;
  392. parts [5] = epilog;
  393. prolog.Append ("namespace ASP {\n" +
  394. "\tusing System;\n" +
  395. "\tusing System.Collections;\n" +
  396. "\tusing System.Collections.Specialized;\n" +
  397. "\tusing System.Configuration;\n" +
  398. "\tusing System.IO;\n" +
  399. "\tusing System.Text;\n" +
  400. "\tusing System.Text.RegularExpressions;\n" +
  401. "\tusing System.Web;\n" +
  402. "\tusing System.Web.Caching;\n" +
  403. "\tusing System.Web.Security;\n" +
  404. "\tusing System.Web.SessionState;\n" +
  405. "\tusing System.Web.UI;\n" +
  406. "\tusing System.Web.UI.WebControls;\n" +
  407. "\tusing System.Web.UI.HtmlControls;\n");
  408. declarations.Append ("\t\tprivate static int __autoHandlers;\n");
  409. current_function.Append ("\t\tprivate void __BuildControlTree (System.Web.UI.Control __ctrl)\n\t\t{\n");
  410. if (!IsUserControl)
  411. current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
  412. "(System.Web.UI.IParserAccessor) __ctrl;\n\n");
  413. else
  414. controls.UseCodeRender = true;
  415. }
  416. public TextReader GetCode ()
  417. {
  418. if (!parse_ok)
  419. throw new InvalidOperationException ("Parsing not done yet! (may be there were errors?)");
  420. StringBuilder code = new StringBuilder ();
  421. for (int i = 0; i < parts.Length; i++)
  422. code.Append ((StringBuilder) parts [i]);
  423. return new StringReader (code.ToString ());
  424. }
  425. // Regex.Escape () make some illegal escape sequences for a C# source.
  426. private string Escape (string input)
  427. {
  428. if (input == null)
  429. return String.Empty;
  430. string output = input.Replace ("\\", "\\\\");
  431. output = output.Replace ("\"", "\\\"");
  432. output = output.Replace ("\t", "\\t");
  433. output = output.Replace ("\r", "\\r");
  434. output = output.Replace ("\n", "\\n");
  435. output = output.Replace ("\n", "\\n");
  436. return output;
  437. }
  438. bool AddProtectedField (Type type, string fieldName)
  439. {
  440. if (parentType == null) {
  441. declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
  442. return true;
  443. }
  444. FieldInfo field = parentType.GetField (fieldName, BindingFlags.Public |
  445. BindingFlags.NonPublic |
  446. BindingFlags.Instance |
  447. BindingFlags.Static);
  448. if (field == null || (!field.IsPublic && !field.IsFamily)) {
  449. declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
  450. return true;
  451. }
  452. if (!field.FieldType.IsAssignableFrom (type)) {
  453. string message = String.Format ("The base class includes the field '{0}', but its " +
  454. "type '{1}' is not compatible with {2}",
  455. fieldName, field.FieldType, type);
  456. throw new ApplicationException (message);
  457. }
  458. return false;
  459. }
  460. private Type LoadParentType (string typeName)
  461. {
  462. // First try loaded assemblies, then try assemblies in Bin directory.
  463. // By now i do this 'by hand' but may be this is a runtime/gac task.
  464. Type type = null;
  465. Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
  466. foreach (Assembly ass in assemblies) {
  467. type = ass.GetType (typeName);
  468. if (type != null)
  469. return type;
  470. }
  471. Assembly assembly;
  472. string [] binDlls = Directory.GetFiles (privateBinPath, "*.dll");
  473. foreach (string dll in binDlls) {
  474. string dllPath = Path.Combine (privateBinPath, dll);
  475. assembly = null;
  476. try {
  477. assembly = Assembly.LoadFrom (dllPath);
  478. type = assembly.GetType (typeName);
  479. } catch (Exception e) {
  480. if (assembly != null) {
  481. Console.WriteLine ("ASP.NET Warning: assembly {0} loaded", dllPath);
  482. Console.WriteLine ("ASP.NET Warning: but type {0} not found", typeName);
  483. } else {
  484. Console.WriteLine ("ASP.NET Warning: unable to load type {0} from {1}",
  485. typeName, dllPath);
  486. }
  487. Console.WriteLine ("ASP.NET Warning: error was: {0}", e.Message);
  488. }
  489. if (type != null)
  490. return type;
  491. }
  492. return null;
  493. }
  494. private void PageDirective (TagAttributes att)
  495. {
  496. if (att ["ClassName"] != null){
  497. this.className = (string) att ["ClassName"];
  498. Options ["ClassName"] = className;
  499. }
  500. if (att ["EnableSessionState"] != null){
  501. if (!IsPage)
  502. throw new ApplicationException ("EnableSessionState not allowed here.");
  503. string est = (string) att ["EnableSessionState"];
  504. if (0 == String.Compare (est, "false", true))
  505. sessionState = SessionState.Disabled;
  506. else if (0 == String.Compare (est, "true", true))
  507. sessionState = SessionState.Enabled;
  508. else if (0 == String.Compare (est, "readonly", true))
  509. sessionState = SessionState.ReadOnly;
  510. else
  511. throw new ApplicationException ("EnableSessionState in Page directive not set to " +
  512. "a correct value: " + est);
  513. }
  514. if (att ["Inherits"] != null) {
  515. parent = (string) att ["Inherits"];
  516. parentType = LoadParentType (parent);
  517. if (parentType == null)
  518. throw new ApplicationException ("The class " + parent + " cannot be found.");
  519. }
  520. if (att ["CompilerOptions"] != null)
  521. Options ["CompilerOptions"] = (string) att ["CompilerOptions"];
  522. if (att ["AutoEventWireup"] != null) {
  523. if (options ["AutoEventWireup"] != null)
  524. throw new ApplicationException ("Already have an AutoEventWireup attribute");
  525. bool autoevent = true;
  526. string v = att ["AutoEventWireup"] as string;
  527. try {
  528. autoevent = Convert.ToBoolean (v);
  529. } catch (Exception) {
  530. throw new ApplicationException ("'" + v + "' is not a valid value for AutoEventWireup");
  531. }
  532. options ["AutoEventWireup"] = autoevent;
  533. }
  534. //FIXME: add support for more attributes.
  535. }
  536. void AddReference (string dll)
  537. {
  538. string references = Options ["References"] as string;
  539. if (references == null)
  540. references = dll;
  541. else
  542. references = references + "|" + dll;
  543. Options ["References"] = references;
  544. }
  545. private void RegisterDirective (TagAttributes att)
  546. {
  547. string tag_prefix = (string) (att ["tagprefix"] == null ? "" : att ["tagprefix"]);
  548. string name_space = (string) (att ["namespace"] == null ? "" : att ["namespace"]);
  549. string assembly_name = (string) (att ["assembly"] == null ? "" : att ["assembly"]);
  550. string tag_name = (string) (att ["tagname"] == null ? "" : att ["tagname"]);
  551. string src = (string) (att ["src"] == null ? "" : att ["src"]);
  552. if (tag_prefix != "" && name_space != "" && assembly_name != ""){
  553. if (tag_name != "" || src != "")
  554. throw new ApplicationException ("Invalid attributes for @ Register: " +
  555. att.ToString ());
  556. AddUsing (name_space);
  557. string dll = privateBinPath + Path.DirectorySeparatorChar + assembly_name + ".dll";
  558. // Hack: it should use assembly.load semantics...
  559. // may be when we don't run mcs as a external program...
  560. if (!File.Exists (dll))
  561. dll = assembly_name;
  562. Foundry.RegisterFoundry (tag_prefix, dll, name_space);
  563. AddReference (dll);
  564. return;
  565. }
  566. if (tag_prefix != "" && tag_name != "" && src != ""){
  567. if (name_space != "" && assembly_name != "")
  568. throw new ApplicationException ("Invalid attributes for @ Register: " +
  569. att.ToString ());
  570. if (!src.EndsWith (".ascx"))
  571. throw new ApplicationException ("Source file extension for controls " +
  572. "must be .ascx");
  573. UserControlData data = GenerateUserControl (src, Context);
  574. switch (data.result) {
  575. case UserControlResult.OK:
  576. AddUsing ("ASP");
  577. Foundry.RegisterFoundry (tag_prefix, tag_name, data.assemblyName, "ASP", data.className);
  578. AddReference (data.assemblyName);
  579. break;
  580. case UserControlResult.FileNotFound:
  581. throw new ApplicationException ("File '" + src + "' not found.");
  582. case UserControlResult.CompilationFailed:
  583. //TODO: should say where the generated .cs file is for the server to
  584. //show the source and the compiler error
  585. throw new NotImplementedException ();
  586. }
  587. return;
  588. }
  589. throw new ApplicationException ("Invalid combination of attributes in " +
  590. "@ Register: " + att.ToString ());
  591. }
  592. private void ProcessDirective ()
  593. {
  594. FlushPlainText ();
  595. Directive directive = (Directive) current;
  596. TagAttributes att = directive.Attributes;
  597. if (att == null)
  598. return;
  599. string value;
  600. string id = directive.TagID.ToUpper ();
  601. switch (id){
  602. case "APPLICATION":
  603. if (main_directive != null)
  604. throw new ApplicationException (id + " not allowed after " + main_directive);
  605. if (!IsApplication)
  606. throw new ApplicationException ("@Application not allowed.");
  607. string inherits = att ["inherits"] as string;
  608. if (inherits != null)
  609. Options ["Inherits"] = inherits;
  610. main_directive = directive.TagID;
  611. break;
  612. case "PAGE":
  613. case "CONTROL":
  614. if (main_directive != null)
  615. throw new ApplicationException (id + " not allowed after " + main_directive);
  616. if (IsUserControl && id != "CONTROL")
  617. throw new ApplicationException ("@Page not allowed for user controls.");
  618. else if (IsPage && id != "PAGE")
  619. throw new ApplicationException ("@Control not allowed here. This is a page!");
  620. PageDirective (att);
  621. main_directive = directive.TagID;
  622. break;
  623. case "IMPORT":
  624. value = att ["namespace"] as string;
  625. if (value == null || att.Count > 1)
  626. throw new ApplicationException ("Wrong syntax in Import directive.");
  627. string _using = "using " + value + ";";
  628. if (AddUsing (value) == true) {
  629. string imports = Options ["Import"] as string;
  630. if (imports == null) {
  631. imports = value;
  632. } else {
  633. imports += "," + value;
  634. }
  635. Options ["Import"] = imports;
  636. }
  637. break;
  638. case "IMPLEMENTS":
  639. if (IsApplication)
  640. throw new ApplicationException ("@ Implements not allowed in an application file.");
  641. string iface = (string) att ["interface"];
  642. AddInterface (iface);
  643. break;
  644. case "REGISTER":
  645. if (IsApplication)
  646. throw new ApplicationException ("@ Register not allowed in an application file.");
  647. RegisterDirective (att);
  648. break;
  649. case "ASSEMBLY":
  650. if (att.Count > 1)
  651. throw new ApplicationException ("Wrong syntax in Assembly directive.");
  652. string name = att ["name"] as string;
  653. string src = att ["src"] as string;
  654. if (name == null && src == null)
  655. throw new ApplicationException ("Wrong syntax in Assembly directive.");
  656. if (IsApplication && src != null)
  657. throw new ApplicationException ("'name' attribute expected.");
  658. value = (name == null) ? src : name;
  659. string assemblies = Options ["Assembly"] as string;
  660. if (assemblies == null) {
  661. assemblies = value;
  662. } else {
  663. assemblies += "," + value;
  664. }
  665. Options ["Assembly"] = assemblies;
  666. break;
  667. }
  668. }
  669. private void ProcessPlainText ()
  670. {
  671. PlainText asis = (PlainText) current;
  672. string trimmed = asis.Text.Trim ();
  673. if (trimmed == String.Empty && controls.SpaceBetweenTags == true)
  674. return;
  675. if (IsApplication) {
  676. if (trimmed != String.Empty)
  677. throw new ApplicationException (app_file_wrong);
  678. return;
  679. }
  680. if (trimmed != String.Empty && controls.PeekChildKind () != ChildrenKind.CONTROLS){
  681. string tag_id = controls.PeekTagID ();
  682. throw new ApplicationException ("Literal content not allowed for " + tag_id);
  683. }
  684. string escaped_text = Escape (asis.Text);
  685. current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject (" +
  686. "new System.Web.UI.LiteralControl (\"{0}\"));\n",
  687. escaped_text);
  688. StringBuilder codeRenderFunction = controls.CodeRenderFunction;
  689. codeRenderFunction.AppendFormat ("\t\t\t__output.Write (\"{0}\");\n", escaped_text);
  690. }
  691. private string EnumValueNameToString (Type enum_type, string value_name)
  692. {
  693. if (value_name.EndsWith ("*"))
  694. throw new ApplicationException ("Invalid property value: '" + value_name +
  695. ". It must be a valid " + enum_type.ToString () + " value.");
  696. MemberInfo [] nested_types = enum_type.FindMembers (MemberTypes.Field,
  697. BindingFlags.Public | BindingFlags.Static,
  698. Type.FilterNameIgnoreCase,
  699. value_name);
  700. if (nested_types.Length == 0)
  701. throw new ApplicationException ("Value " + value_name + " not found in enumeration " +
  702. enum_type.ToString ());
  703. if (nested_types.Length > 1)
  704. throw new ApplicationException ("Value " + value_name + " found " +
  705. nested_types.Length + " in enumeration " +
  706. enum_type.ToString ());
  707. return enum_type.ToString () + "." + nested_types [0].Name;
  708. }
  709. private void NewControlFunction (string tag_id,
  710. string control_id,
  711. Type control_type,
  712. ChildrenKind children_kind,
  713. string defaultPropertyName)
  714. {
  715. ChildrenKind prev_children_kind = controls.PeekChildKind ();
  716. if (prev_children_kind == ChildrenKind.NONE ||
  717. prev_children_kind == ChildrenKind.PROPERTIES){
  718. string prev_tag_id = controls.PeekTagID ();
  719. throw new ApplicationException ("Child controls not allowed for " + prev_tag_id);
  720. }
  721. Type allowed = null;
  722. if (prev_children_kind == ChildrenKind.DBCOLUMNS &&
  723. !typeof (DataGridColumn).IsAssignableFrom (control_type)) {
  724. allowed = typeof (DataGridColumn);
  725. } else if (prev_children_kind == ChildrenKind.LISTITEM &&
  726. control_type != typeof (System.Web.UI.WebControls.ListItem)) {
  727. allowed = typeof (DataGridColumn);
  728. } else if (prev_children_kind == ChildrenKind.HTMLROW) {
  729. Type prevType = controls.PeekType ();
  730. if (prevType == typeof (HtmlTable) && control_type != typeof (HtmlTableRow))
  731. allowed = typeof (HtmlTableRow);
  732. else if (prevType == typeof (Table) && control_type != typeof (TableRow))
  733. allowed = typeof (TableRow);
  734. } else if (prev_children_kind == ChildrenKind.HTMLCELL) {
  735. Type prevType = controls.PeekType ();
  736. if (prevType == typeof (HtmlTableRow) && control_type != typeof (HtmlTableCell))
  737. allowed = typeof (HtmlTableCell);
  738. else if (prevType == typeof (TableRow) && control_type != typeof (TableCell))
  739. allowed = typeof (TableCell);
  740. }
  741. if (allowed != null)
  742. throw new ApplicationException ("Inside " + controls.PeekTagID () + " only " +
  743. allowed + " objects are allowed");
  744. StringBuilder func_code = new StringBuilder ();
  745. current_function = func_code;
  746. if (0 == String.Compare (tag_id, "form", true)){
  747. if (has_form_tag)
  748. throw new ApplicationException ("Only one form server tag allowed.");
  749. has_form_tag = true;
  750. }
  751. controls.Push (control_type, control_id, tag_id, children_kind, defaultPropertyName);
  752. bool is_generic = control_type == typeof (System.Web.UI.HtmlControls.HtmlGenericControl);
  753. functions.Push (current_function);
  754. if (control_type != typeof (System.Web.UI.WebControls.ListItem) &&
  755. prev_children_kind != ChildrenKind.DBCOLUMNS) {
  756. current_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_" +
  757. "{0} ()\n\t\t{{\n\t\t\t{1} __ctrl;\n\n\t\t\t__ctrl" +
  758. " = new {1} ({2});\n\t\t\tthis.{0} = __ctrl;\n",
  759. control_id, control_type,
  760. (is_generic? "\"" + tag_id + "\"" : ""));
  761. } else {
  762. current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ()\n\t\t{{" +
  763. "\n\t\t\t{1} __ctrl;\n\t\t\t__ctrl = new {1} ();" +
  764. "\n\t\t\tthis.{0} = __ctrl;\n",
  765. control_id, control_type);
  766. }
  767. if (children_kind == ChildrenKind.CONTROLS || children_kind == ChildrenKind.OPTION)
  768. current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
  769. "(System.Web.UI.IParserAccessor) __ctrl;\n");
  770. }
  771. private void DataBoundProperty (Type target, string varName, string value)
  772. {
  773. if (value == "")
  774. throw new ApplicationException ("Empty data binding tag.");
  775. string control_id = controls.PeekControlID ();
  776. string control_type_string = controls.PeekType ().ToString ();
  777. StringBuilder db_function = controls.DataBindFunction;
  778. string container;
  779. if (controls.Container == null || !typeof (INamingContainer).IsAssignableFrom (controls.Container))
  780. container = "System.Web.UI.Control";
  781. else {
  782. container = controls.Container.ToString ();
  783. }
  784. if (db_function.Length == 0)
  785. db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
  786. "System.EventArgs e) {{\n" +
  787. "\t\t\t{1} Container;\n" +
  788. "\t\t\t{2} target;\n" +
  789. "\t\t\ttarget = ({2}) sender;\n" +
  790. "\t\t\tContainer = ({1}) target.BindingContainer;\n",
  791. control_id, container, control_type_string);
  792. /* Removes '<%#' and '%>' */
  793. string real_value = value.Remove (0,3);
  794. real_value = real_value.Remove (real_value.Length - 2, 2);
  795. real_value = real_value.Trim ();
  796. if (target == typeof (string))
  797. db_function.AppendFormat ("\t\t\ttarget.{0} = System.Convert.ToString ({1});\n",
  798. varName, real_value);
  799. else
  800. db_function.AppendFormat ("\t\t\ttarget.{0} = ({1}) ({2});\n",
  801. varName, target, real_value);
  802. }
  803. /*
  804. * Returns true if it generates some code for the specified property
  805. */
  806. private void AddCodeForPropertyOrField (Type type, string var_name, string att, bool isDataBound)
  807. {
  808. /* FIXME: should i check for this or let the compiler fail?
  809. * if (!prop.CanWrite)
  810. * ....
  811. */
  812. if (isDataBound) {
  813. DataBoundProperty (type, var_name, att);
  814. }
  815. else if (type == typeof (string)){
  816. if (att == null)
  817. throw new ApplicationException ("null value for attribute " + var_name );
  818. current_function.AppendFormat ("\t\t\t__ctrl.{0} = \"{1}\";\n", var_name,
  819. Escape (att)); // FIXME: really Escape this?
  820. }
  821. else if (type.IsEnum){
  822. if (att == null)
  823. throw new ApplicationException ("null value for attribute " + var_name );
  824. string enum_value = EnumValueNameToString (type, att);
  825. current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, enum_value);
  826. }
  827. else if (type == typeof (bool)){
  828. string value;
  829. if (att == null)
  830. value = "true"; //FIXME: is this ok for non Style properties?
  831. else if (0 == String.Compare (att, "true", true))
  832. value = "true";
  833. else if (0 == String.Compare (att, "false", true))
  834. value = "false";
  835. else
  836. throw new ApplicationException ("Value '" + att + "' is not a valid boolean.");
  837. current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
  838. }
  839. else if (type == typeof (System.Web.UI.WebControls.Unit)){
  840. //FIXME: should use the culture specified in Page
  841. try {
  842. Unit value = Unit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
  843. } catch (Exception) {
  844. throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
  845. }
  846. current_function.AppendFormat ("\t\t\t__ctrl.{0} = " +
  847. "System.Web.UI.WebControls.Unit.Parse (\"{1}\", " +
  848. "System.Globalization.CultureInfo.InvariantCulture);\n",
  849. var_name, att);
  850. }
  851. else if (type == typeof (System.Web.UI.WebControls.FontUnit)){
  852. //FIXME: should use the culture specified in Page
  853. try {
  854. FontUnit value = FontUnit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
  855. } catch (Exception) {
  856. throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
  857. }
  858. current_function.AppendFormat ("\t\t\t__ctrl.{0} = " +
  859. "System.Web.UI.WebControls.FontUnit.Parse (\"{1}\", " +
  860. "System.Globalization.CultureInfo.InvariantCulture);\n",
  861. var_name, att);
  862. }
  863. else if (type == typeof (Int16) || type == typeof (Int32) || type == typeof (Int64)) {
  864. long value;
  865. try {
  866. value = Int64.Parse (att); //FIXME: should use the culture specified in Page
  867. } catch (Exception){
  868. throw new ApplicationException (att + " is not a valid signed number " +
  869. "or is out of range.");
  870. }
  871. current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
  872. }
  873. else if (type == typeof (UInt16) || type == typeof (UInt32) || type == typeof (UInt64)) {
  874. ulong value;
  875. try {
  876. value = UInt64.Parse (att); //FIXME: should use the culture specified in Page
  877. } catch (Exception){
  878. throw new ApplicationException (att + " is not a valid unsigned number " +
  879. "or is out of range.");
  880. }
  881. current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
  882. }
  883. else if (type == typeof (float)) {
  884. float value;
  885. try {
  886. value = Single.Parse (att);
  887. } catch (Exception){
  888. throw new ApplicationException (att + " is not avalid float number or " +
  889. "is out of range.");
  890. }
  891. current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
  892. }
  893. else if (type == typeof (double)){
  894. double value;
  895. try {
  896. value = Double.Parse (att);
  897. } catch (Exception){
  898. throw new ApplicationException (att + " is not avalid double number or " +
  899. "is out of range.");
  900. }
  901. current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
  902. }
  903. else if (type == typeof (System.Drawing.Color)){
  904. Color c;
  905. try {
  906. c = (Color) TypeDescriptor.GetConverter (typeof (Color)).ConvertFromString (att);
  907. } catch (Exception e){
  908. throw new ApplicationException ("Color " + att + " is not a valid color.", e);
  909. }
  910. // Should i also test for IsSystemColor?
  911. // Are KnownColor members in System.Drawing.Color?
  912. if (c.IsKnownColor){
  913. current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
  914. "{1};\n", var_name, c.Name);
  915. }
  916. else {
  917. current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
  918. "FromArgb ({1}, {2}, {3}, {4});\n",
  919. var_name, c.A, c.R, c.G, c.B);
  920. }
  921. }
  922. else if (type == typeof (string [])) {
  923. string [] subStrings = att.Split (',');
  924. current_function.AppendFormat ("\t\t\t__ctrl.{0} = new String [] {{\n", var_name);
  925. int end = subStrings.Length;
  926. for (int i = 0; i < end; i++) {
  927. string s = subStrings [i].Trim ();
  928. current_function.AppendFormat ("\t\t\t\t\"{0}\"", s);
  929. if (i == end - 1)
  930. current_function.Append ("\t\t\t\t};\n");
  931. else
  932. current_function.Append (",\n");
  933. }
  934. } else {
  935. throw new ApplicationException ("Unsupported type in property: " +
  936. type.ToString ());
  937. }
  938. }
  939. private bool ProcessPropertiesAndFields (MemberInfo member, string id, TagAttributes att)
  940. {
  941. int hyphen = id.IndexOf ('-');
  942. bool isPropertyInfo = (member is PropertyInfo);
  943. bool is_processed = false;
  944. bool isDataBound = att.IsDataBound ((string) att [id]);
  945. Type type;
  946. if (isPropertyInfo) {
  947. type = ((PropertyInfo) member).PropertyType;
  948. if (hyphen == -1 && ((PropertyInfo) member).CanWrite == false)
  949. return false;
  950. } else {
  951. type = ((FieldInfo) member).FieldType;
  952. }
  953. if (0 == String.Compare (member.Name, id, true)){
  954. AddCodeForPropertyOrField (type, member.Name, (string) att [id], isDataBound);
  955. is_processed = true;
  956. } else if (hyphen != -1 && (type == fontinfoType || type == styleType || type.IsSubclassOf (styleType))){
  957. string prop_field = id.Replace ("-", ".");
  958. string [] parts = prop_field.Split (new char [] {'.'});
  959. if (parts.Length != 2 || 0 != String.Compare (member.Name, parts [0], true))
  960. return false;
  961. PropertyInfo [] subprops = type.GetProperties ();
  962. foreach (PropertyInfo subprop in subprops){
  963. if (0 != String.Compare (subprop.Name, parts [1], true))
  964. continue;
  965. if (subprop.CanWrite == false)
  966. return false;
  967. bool is_bool = subprop.PropertyType == typeof (bool);
  968. if (!is_bool && att [id] == null){
  969. att [id] = ""; // Font-Size -> Font-Size="" as html
  970. return false;
  971. }
  972. string value;
  973. if (att [id] == null && is_bool)
  974. value = "true"; // Font-Bold <=> Font-Bold="true"
  975. else
  976. value = (string) att [id];
  977. AddCodeForPropertyOrField (subprop.PropertyType,
  978. member.Name + "." + subprop.Name,
  979. value, isDataBound);
  980. is_processed = true;
  981. }
  982. }
  983. return is_processed;
  984. }
  985. private void AddCodeForAttributes (Type type, TagAttributes att)
  986. {
  987. EventInfo [] ev_info = type.GetEvents ();
  988. PropertyInfo [] prop_info = type.GetProperties ();
  989. FieldInfo [] field_info = type.GetFields ();
  990. bool is_processed = false;
  991. ArrayList processed = new ArrayList ();
  992. foreach (string id in att.Keys){
  993. if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
  994. continue;
  995. if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
  996. string id_as_event = id.Substring (2);
  997. foreach (EventInfo ev in ev_info){
  998. if (0 == String.Compare (ev.Name, id_as_event, true)){
  999. current_function.AppendFormat (
  1000. "\t\t\t__ctrl.{0} += " +
  1001. "new {1} (this.{2});\n",
  1002. ev.Name, ev.EventHandlerType, att [id]);
  1003. is_processed = true;
  1004. break;
  1005. }
  1006. }
  1007. if (is_processed){
  1008. is_processed = false;
  1009. continue;
  1010. }
  1011. }
  1012. foreach (PropertyInfo prop in prop_info){
  1013. is_processed = ProcessPropertiesAndFields (prop, id, att);
  1014. if (is_processed)
  1015. break;
  1016. }
  1017. if (!is_processed) {
  1018. foreach (FieldInfo field in field_info){
  1019. is_processed = ProcessPropertiesAndFields (field, id, att);
  1020. if (is_processed)
  1021. break;
  1022. }
  1023. }
  1024. if (is_processed){
  1025. is_processed = false;
  1026. continue;
  1027. }
  1028. current_function.AppendFormat ("\t\t\t((System.Web.UI.IAttributeAccessor) __ctrl)." +
  1029. "SetAttribute (\"{0}\", \"{1}\");\n",
  1030. id, Escape ((string) att [id]));
  1031. }
  1032. }
  1033. private void AddCodeRenderControl (StringBuilder function)
  1034. {
  1035. AddCodeRenderControl (function, controls.CodeRenderIndex);
  1036. }
  1037. private void AddCodeRenderControl (StringBuilder function, int index)
  1038. {
  1039. function.AppendFormat ("\t\t\tparameterContainer.Controls [{0}]." +
  1040. "RenderControl (__output);\n", index);
  1041. }
  1042. private void AddRenderMethodDelegate (StringBuilder function, string control_id)
  1043. {
  1044. function.AppendFormat ("\t\t\t__ctrl.SetRenderMethodDelegate (new System.Web." +
  1045. "UI.RenderMethod (this.__Render_{0}));\n", control_id);
  1046. }
  1047. private void AddCodeRenderFunction (string codeRender, string control_id)
  1048. {
  1049. StringBuilder codeRenderFunction = new StringBuilder ();
  1050. codeRenderFunction.AppendFormat ("\t\tprivate void __Render_{0} " +
  1051. "(System.Web.UI.HtmlTextWriter __output, " +
  1052. "System.Web.UI.Control parameterContainer)\n" +
  1053. "\t\t{{\n", control_id);
  1054. codeRenderFunction.Append (codeRender);
  1055. codeRenderFunction.Append ("\t\t}\n\n");
  1056. init_funcs.Append (codeRenderFunction);
  1057. }
  1058. private void RemoveLiterals (StringBuilder function)
  1059. {
  1060. string no_literals = Regex.Replace (function.ToString (),
  1061. @"\t\t\t__parser.AddParsedSubObject \(" +
  1062. @"new System.Web.UI.LiteralControl \(.+\);\n", "");
  1063. function.Length = 0;
  1064. function.Append (no_literals);
  1065. }
  1066. private bool FinishControlFunction (string tag_id)
  1067. {
  1068. if (functions.Count == 0)
  1069. throw new ApplicationException ("Unbalanced open/close tags");
  1070. if (controls.Count == 0)
  1071. return false;
  1072. string saved_id = controls.PeekTagID ();
  1073. if (0 != String.Compare (saved_id, tag_id, true))
  1074. return false;
  1075. FlushPlainText ();
  1076. StringBuilder old_function = (StringBuilder) functions.Pop ();
  1077. current_function = (StringBuilder) functions.Peek ();
  1078. string control_id = controls.PeekControlID ();
  1079. Type control_type = controls.PeekType ();
  1080. ChildrenKind child_kind = controls.PeekChildKind ();
  1081. bool hasDataBindFunction = controls.HasDataBindFunction ();
  1082. if (hasDataBindFunction)
  1083. old_function.AppendFormat ("\t\t\t__ctrl.DataBinding += new System.EventHandler " +
  1084. "(this.__DataBind_{0});\n", control_id);
  1085. bool useCodeRender = controls.UseCodeRender;
  1086. if (useCodeRender)
  1087. AddRenderMethodDelegate (old_function, control_id);
  1088. if (control_type == typeof (System.Web.UI.ITemplate)){
  1089. old_function.Append ("\n\t\t}\n\n");
  1090. current_function.AppendFormat ("\t\t\t__ctrl.{0} = new System.Web.UI." +
  1091. "CompiledTemplateBuilder (new System.Web.UI." +
  1092. "BuildTemplateMethod (this.__BuildControl_{1}));\n",
  1093. saved_id, control_id);
  1094. }
  1095. else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumnCollection)){
  1096. old_function.Append ("\n\t\t}\n\n");
  1097. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
  1098. control_id, saved_id);
  1099. }
  1100. else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumn) ||
  1101. control_type.IsSubclassOf (typeof (System.Web.UI.WebControls.DataGridColumn)) ||
  1102. control_type == typeof (System.Web.UI.WebControls.ListItem)){
  1103. old_function.Append ("\n\t\t}\n\n");
  1104. string parsed = "";
  1105. string ctrl_name = "ctrl";
  1106. Type cont = controls.Container;
  1107. if (cont == null || cont == typeof (System.Web.UI.HtmlControls.HtmlSelect)){
  1108. parsed = "ParsedSubObject";
  1109. ctrl_name = "parser";
  1110. }
  1111. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
  1112. "\t\t\t__{1}.Add{2} (this.{0});\n\n",
  1113. control_id, ctrl_name, parsed);
  1114. }
  1115. else if (child_kind == ChildrenKind.LISTITEM){
  1116. old_function.Append ("\n\t\t}\n\n");
  1117. init_funcs.Append (old_function); // Closes the BuildList function
  1118. old_function = (StringBuilder) functions.Pop ();
  1119. current_function = (StringBuilder) functions.Peek ();
  1120. old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
  1121. "return __ctrl;\n\t\t}}\n\n",
  1122. control_id, controls.PeekDefaultPropertyName ());
  1123. controls.Pop ();
  1124. control_id = controls.PeekControlID ();
  1125. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
  1126. "AddParsedSubObject (this.{0});\n\n", control_id);
  1127. } else if (control_type == typeof (HtmlTableCell) || control_type == typeof (TableCell)) {
  1128. old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
  1129. object top = controls.Pop ();
  1130. Type t = controls.PeekType ();
  1131. controls.Push (top);
  1132. string parsed = "";
  1133. string ctrl_name = "ctrl";
  1134. if (!t.IsSubclassOf (typeof (WebControl)) && t != typeof (HtmlTableRow)) {
  1135. parsed = "ParsedSubObject";
  1136. ctrl_name = "parser";
  1137. }
  1138. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
  1139. "\t\t\t__{1}.Add{2} (this.{0});\n\n",
  1140. control_id, ctrl_name, parsed);
  1141. } else if (child_kind == ChildrenKind.HTMLROW || child_kind == ChildrenKind.HTMLCELL) {
  1142. old_function.Append ("\n\t\t}\n\n");
  1143. init_funcs.Append (old_function);
  1144. old_function = (StringBuilder) functions.Pop ();
  1145. current_function = (StringBuilder) functions.Peek ();
  1146. old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
  1147. "return __ctrl;\n\t\t}}\n\n",
  1148. control_id, controls.PeekDefaultPropertyName ());
  1149. controls.Pop ();
  1150. control_id = controls.PeekControlID ();
  1151. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n", control_id);
  1152. if (child_kind == ChildrenKind.HTMLROW) {
  1153. current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject ({0});\n",
  1154. control_id);
  1155. } else {
  1156. current_function.AppendFormat ("\t\t\t__ctrl.Add (this.{0});\n", control_id);
  1157. }
  1158. } else {
  1159. old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
  1160. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
  1161. "AddParsedSubObject (this.{0});\n\n", control_id);
  1162. }
  1163. if (useCodeRender)
  1164. RemoveLiterals (old_function);
  1165. init_funcs.Append (old_function);
  1166. if (useCodeRender)
  1167. AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), control_id);
  1168. if (hasDataBindFunction){
  1169. StringBuilder db_function = controls.DataBindFunction;
  1170. db_function.Append ("\t\t}\n\n");
  1171. init_funcs.Append (db_function);
  1172. }
  1173. // Avoid getting empty stacks for unbalanced open/close tags
  1174. if (controls.Count > 1){
  1175. controls.Pop ();
  1176. AddCodeRenderControl (controls.CodeRenderFunction, controls.ChildIndex);
  1177. }
  1178. return true;
  1179. }
  1180. private void NewTableElementFunction (HtmlControlTag ctrl)
  1181. {
  1182. string control_id = Tag.GetDefaultID ();
  1183. ChildrenKind child_kind;
  1184. Type t;
  1185. if (ctrl.ControlType == typeof (HtmlTable)) {
  1186. t = typeof (HtmlTableRowCollection);
  1187. child_kind = ChildrenKind.HTMLROW;
  1188. } else {
  1189. t = typeof (HtmlTableCellCollection);
  1190. child_kind = ChildrenKind.HTMLCELL;
  1191. }
  1192. controls.Push (ctrl.ControlType,
  1193. control_id,
  1194. ctrl.TagID,
  1195. child_kind,
  1196. ctrl.ParseChildren);
  1197. current_function = new StringBuilder ();
  1198. functions.Push (current_function);
  1199. current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
  1200. "\t\t{{\n", control_id, t);
  1201. }
  1202. private void ProcessHtmlControlTag ()
  1203. {
  1204. FlushPlainText ();
  1205. HtmlControlTag html_ctrl = (HtmlControlTag) current;
  1206. if (html_ctrl.TagID.ToUpper () == "SCRIPT"){
  1207. //FIXME: if the is script is to be read from disk, do it!
  1208. if (html_ctrl.SelfClosing)
  1209. throw new ApplicationException ("Read script from file not supported yet.");
  1210. sstatus = ScriptStatus.Open;
  1211. return;
  1212. }
  1213. if (IsApplication)
  1214. throw new ApplicationException (app_file_wrong);
  1215. Type controlType = html_ctrl.ControlType;
  1216. AddProtectedField (controlType, html_ctrl.ControlID);
  1217. ChildrenKind children_kind;
  1218. if (0 == String.Compare (html_ctrl.TagID, "table", true))
  1219. children_kind = ChildrenKind.HTMLROW;
  1220. else if (0 == String.Compare (html_ctrl.TagID, "tr", true))
  1221. children_kind = ChildrenKind.HTMLCELL;
  1222. else if (0 != String.Compare (html_ctrl.TagID, "select", true))
  1223. children_kind = html_ctrl.IsContainer ? ChildrenKind.CONTROLS :
  1224. ChildrenKind.NONE;
  1225. else
  1226. children_kind = ChildrenKind.OPTION;
  1227. NewControlFunction (html_ctrl.TagID, html_ctrl.ControlID, controlType, children_kind, html_ctrl.ParseChildren);
  1228. current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", html_ctrl.ControlID);
  1229. AddCodeForAttributes (html_ctrl.ControlType, html_ctrl.Attributes);
  1230. if (children_kind == ChildrenKind.HTMLROW || children_kind == ChildrenKind.HTMLCELL)
  1231. NewTableElementFunction (html_ctrl);
  1232. if (html_ctrl.SelfClosing)
  1233. FinishControlFunction (html_ctrl.TagID);
  1234. }
  1235. // Closing is performed in FinishControlFunction ()
  1236. private void NewBuildListFunction (AspComponent component)
  1237. {
  1238. string control_id = Tag.GetDefaultID ();
  1239. controls.Push (component.ComponentType,
  1240. control_id,
  1241. component.TagID,
  1242. component.ChildrenKind,
  1243. component.DefaultPropertyName);
  1244. Type childType = component.DefaultPropertyType;
  1245. if (childType == null)
  1246. childType = typeof (ListItemCollection);
  1247. current_function = new StringBuilder ();
  1248. functions.Push (current_function);
  1249. current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
  1250. "({1} __ctrl)\n" +
  1251. "\t\t{{\n", control_id, childType);
  1252. }
  1253. private void ProcessComponent ()
  1254. {
  1255. FlushPlainText ();
  1256. AspComponent component = (AspComponent) current;
  1257. Type component_type = component.ComponentType;
  1258. AddProtectedField (component_type, component.ControlID);
  1259. NewControlFunction (component.TagID, component.ControlID, component_type,
  1260. component.ChildrenKind, component.DefaultPropertyName);
  1261. if (component_type == typeof (UserControl) ||
  1262. component_type.IsSubclassOf (typeof (System.Web.UI.UserControl)))
  1263. current_function.Append ("\t\t\t__ctrl.InitializeAsUserControl (Page);\n");
  1264. if (component_type == typeof (Control) ||
  1265. component_type.IsSubclassOf (typeof (System.Web.UI.Control)))
  1266. current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", component.ControlID);
  1267. AddCodeForAttributes (component.ComponentType, component.Attributes);
  1268. if (component.ChildrenKind == ChildrenKind.LISTITEM || component.DefaultPropertyType != null)
  1269. NewBuildListFunction (component);
  1270. if (component.SelfClosing)
  1271. FinishControlFunction (component.TagID);
  1272. }
  1273. private void ProcessServerObjectTag ()
  1274. {
  1275. FlushPlainText ();
  1276. ServerObjectTag obj = (ServerObjectTag) current;
  1277. declarations.AppendFormat ("\t\tprivate {0} cached{1};\n", obj.ObjectClass, obj.ObjectID);
  1278. constructor.AppendFormat ("\n\t\tprivate {0} {1}\n\t\t{{\n\t\t\tget {{\n\t\t\t\t" +
  1279. "if (this.cached{1} == null)\n\t\t\t\t\tthis.cached{1} = " +
  1280. "new {0} ();\n\t\t\t\treturn cached{1};\n\t\t\t}}\n\t\t}}\n\n",
  1281. obj.ObjectClass, obj.ObjectID);
  1282. }
  1283. // Creates a new function that sets the values of subproperties.
  1284. private void NewStyleFunction (PropertyTag tag)
  1285. {
  1286. current_function = new StringBuilder ();
  1287. string prop_id = tag.PropertyID;
  1288. Type prop_type = tag.PropertyType;
  1289. // begin function
  1290. current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
  1291. "\t\t{{\n", prop_id, prop_type);
  1292. // Add property initialization code
  1293. PropertyInfo [] subprop_info = prop_type.GetProperties ();
  1294. TagAttributes att = tag.Attributes;
  1295. string subprop_name = null;
  1296. foreach (string id in att.Keys){
  1297. if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
  1298. continue;
  1299. bool is_processed = false;
  1300. foreach (PropertyInfo subprop in subprop_info){
  1301. is_processed = ProcessPropertiesAndFields (subprop, id, att);
  1302. if (is_processed){
  1303. subprop_name = subprop.Name;
  1304. break;
  1305. }
  1306. }
  1307. if (subprop_name == null)
  1308. throw new ApplicationException ("Property " + tag.TagID + " does not have " +
  1309. "a " + id + " subproperty.");
  1310. }
  1311. // Finish function
  1312. current_function.Append ("\n\t\t}\n\n");
  1313. init_funcs.Append (current_function);
  1314. current_function = (StringBuilder) functions.Peek ();
  1315. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
  1316. prop_id, tag.PropertyName);
  1317. if (!tag.SelfClosing){
  1318. // Next tag should be the closing tag
  1319. controls.Push (null, null, null, ChildrenKind.NONE, null);
  1320. waitClosing = tag.TagID;
  1321. }
  1322. }
  1323. // This one just opens the function. Closing is performed in FinishControlFunction ()
  1324. private void NewTemplateFunction (PropertyTag tag)
  1325. {
  1326. /*
  1327. * FIXME
  1328. * This function does almost the same as NewControlFunction.
  1329. * Consider merging.
  1330. */
  1331. string prop_id = tag.PropertyID;
  1332. Type prop_type = tag.PropertyType;
  1333. string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
  1334. controls.Push (prop_type, prop_id, tag_id, ChildrenKind.CONTROLS, null);
  1335. current_function = new StringBuilder ();
  1336. functions.Push (current_function);
  1337. current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
  1338. "(System.Web.UI.Control __ctrl)\n" +
  1339. "\t\t{{\n" +
  1340. "\t\t\tSystem.Web.UI.IParserAccessor __parser " +
  1341. "= (System.Web.UI.IParserAccessor) __ctrl;\n" , prop_id);
  1342. }
  1343. // Closing is performed in FinishControlFunction ()
  1344. private void NewDBColumnFunction (PropertyTag tag)
  1345. {
  1346. /*
  1347. * FIXME
  1348. * This function also does almost the same as NewControlFunction.
  1349. * Consider merging.
  1350. */
  1351. string prop_id = tag.PropertyID;
  1352. Type prop_type = tag.PropertyType;
  1353. string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
  1354. controls.Push (prop_type, prop_id, tag_id, ChildrenKind.DBCOLUMNS, null);
  1355. current_function = new StringBuilder ();
  1356. functions.Push (current_function);
  1357. current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
  1358. "(System.Web.UI.WebControls.DataGridColumnCollection __ctrl)\n" +
  1359. "\t\t{{\n", prop_id);
  1360. }
  1361. private void NewPropertyFunction (PropertyTag tag)
  1362. {
  1363. FlushPlainText ();
  1364. if (tag.PropertyType == typeof (System.Web.UI.WebControls.Style) ||
  1365. tag.PropertyType.IsSubclassOf (typeof (System.Web.UI.WebControls.Style)))
  1366. NewStyleFunction (tag);
  1367. else if (tag.PropertyType == typeof (System.Web.UI.ITemplate))
  1368. NewTemplateFunction (tag);
  1369. else if (tag.PropertyType == typeof (System.Web.UI.WebControls.DataGridColumnCollection))
  1370. NewDBColumnFunction (tag);
  1371. else
  1372. throw new ApplicationException ("Other than Style and ITemplate not supported yet. " +
  1373. tag.PropertyType);
  1374. }
  1375. private void ProcessHtmlTag ()
  1376. {
  1377. Tag tag = (Tag) current;
  1378. ChildrenKind child_kind = controls.PeekChildKind ();
  1379. if (child_kind == ChildrenKind.NONE){
  1380. string tag_id = controls.PeekTagID ();
  1381. throw new ApplicationException (tag + " not allowed inside " + tag_id);
  1382. }
  1383. if (child_kind == ChildrenKind.OPTION){
  1384. if (0 != String.Compare (tag.TagID, "option", true))
  1385. throw new ApplicationException ("Only <option> tags allowed inside <select>.");
  1386. string default_id = Tag.GetDefaultID ();
  1387. Type type = typeof (System.Web.UI.WebControls.ListItem);
  1388. AddProtectedField (type, default_id);
  1389. NewControlFunction (tag.TagID, default_id, type, ChildrenKind.CONTROLS, null);
  1390. return;
  1391. }
  1392. if (child_kind == ChildrenKind.CONTROLS) {
  1393. ArrayList tag_elements = tag.GetElements ();
  1394. foreach (Element e in tag_elements) {
  1395. if (e is PlainText) {
  1396. current = e;
  1397. textChunk.Append (((PlainText) e).Text);
  1398. } else if (e is CodeRenderTag) {
  1399. current = e;
  1400. ProcessCodeRenderTag ();
  1401. } else if (e is DataBindingTag) {
  1402. current = e;
  1403. ProcessDataBindingLiteral ();
  1404. } else {
  1405. throw new ApplicationException (fullPath + ": unexpected tag type " + e.GetType ());
  1406. }
  1407. }
  1408. return;
  1409. }
  1410. if (child_kind == ChildrenKind.HTMLROW) {
  1411. if (0 == String.Compare (tag.TagID, "tr", true)) {
  1412. current = new HtmlControlTag (tag);
  1413. ProcessHtmlControlTag ();
  1414. return;
  1415. }
  1416. }
  1417. if (child_kind == ChildrenKind.HTMLCELL) {
  1418. if (0 == String.Compare (tag.TagID, "td", true)) {
  1419. current = new HtmlControlTag (tag);
  1420. ProcessHtmlControlTag ();
  1421. return;
  1422. }
  1423. }
  1424. // Now child_kind should be PROPERTIES, so only allow tag_id == property
  1425. Type control_type = controls.PeekType ();
  1426. PropertyInfo [] prop_info = control_type.GetProperties ();
  1427. bool is_processed = false;
  1428. foreach (PropertyInfo prop in prop_info){
  1429. if (0 == String.Compare (prop.Name, tag.TagID, true)){
  1430. PropertyTag prop_tag = new PropertyTag (tag, prop.PropertyType, prop.Name);
  1431. NewPropertyFunction (prop_tag);
  1432. is_processed = true;
  1433. break;
  1434. }
  1435. }
  1436. if (!is_processed){
  1437. string tag_id = controls.PeekTagID ();
  1438. throw new ApplicationException (tag.TagID + " is not a property of " + control_type);
  1439. }
  1440. }
  1441. private Tag Map (Tag tag)
  1442. {
  1443. int pos = tag.TagID.IndexOf (":");
  1444. if (pos == -1) {
  1445. ChildrenKind child_kind = controls.PeekChildKind ();
  1446. if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
  1447. tag.Attributes.Add ("runat", "server");
  1448. return new HtmlControlTag (tag);
  1449. } else if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
  1450. tag.Attributes.Add ("runat", "server");
  1451. return new HtmlControlTag (tag);
  1452. }
  1453. }
  1454. if (tag is CloseTag ||
  1455. ((tag.Attributes == null ||
  1456. !tag.Attributes.IsRunAtServer ()) && pos == -1))
  1457. return tag;
  1458. if (pos == -1){
  1459. if (0 == String.Compare (tag.TagID, "object", true))
  1460. return new ServerObjectTag (tag);
  1461. return new HtmlControlTag (tag);
  1462. }
  1463. string foundry_name = tag.TagID.Substring (0, pos);
  1464. string component_name = tag.TagID.Substring (pos + 1);
  1465. if (Foundry.LookupFoundry (foundry_name) == false)
  1466. throw new ApplicationException ("Cannot find foundry for alias'" + foundry_name + "'");
  1467. AspComponent component = Foundry.MakeAspComponent (foundry_name, component_name, tag);
  1468. if (component == null)
  1469. throw new ApplicationException ("Cannot find component '" + component_name +
  1470. "' for alias '" + foundry_name + "'");
  1471. return component;
  1472. }
  1473. private void ProcessCloseTag ()
  1474. {
  1475. CloseTag closeTag = (CloseTag) current;
  1476. if (FinishControlFunction (closeTag.TagID))
  1477. return;
  1478. textChunk.Append (closeTag.PlainHtml);
  1479. }
  1480. private void ProcessDataBindingLiteral ()
  1481. {
  1482. FlushPlainText ();
  1483. DataBindingTag dataBinding = (DataBindingTag) current;
  1484. string actual_value = dataBinding.Data;
  1485. if (actual_value == "")
  1486. throw new ApplicationException ("Empty data binding tag.");
  1487. if (controls.PeekChildKind () != ChildrenKind.CONTROLS)
  1488. throw new ApplicationException ("Data bound content not allowed for " +
  1489. controls.PeekTagID ());
  1490. StringBuilder db_function = new StringBuilder ();
  1491. string control_id = Tag.GetDefaultID ();
  1492. string control_type_string = "System.Web.UI.DataBoundLiteralControl";
  1493. AddProtectedField (typeof (System.Web.UI.DataBoundLiteralControl), control_id);
  1494. // Build the control
  1495. db_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_{0} ()\n" +
  1496. "\t\t{{\n\t\t\t{1} __ctrl;\n\n" +
  1497. "\t\t\t__ctrl = new {1} (0, 1);\n" +
  1498. "\t\t\tthis.{0} = __ctrl;\n" +
  1499. "\t\t\t__ctrl.DataBinding += new System.EventHandler " +
  1500. "(this.__DataBind_{0});\n" +
  1501. "\t\t\treturn __ctrl;\n"+
  1502. "\t\t}}\n\n",
  1503. control_id, control_type_string);
  1504. // DataBinding handler
  1505. db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
  1506. "System.EventArgs e) {{\n" +
  1507. "\t\t\t{1} Container;\n" +
  1508. "\t\t\t{2} target;\n" +
  1509. "\t\t\ttarget = ({2}) sender;\n" +
  1510. "\t\t\tContainer = ({1}) target.BindingContainer;\n" +
  1511. "\t\t\ttarget.SetDataBoundString (0, System.Convert." +
  1512. "ToString ({3}));\n" +
  1513. "\t\t}}\n\n",
  1514. control_id, controls.Container, control_type_string,
  1515. actual_value);
  1516. init_funcs.Append (db_function);
  1517. current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
  1518. "AddParsedSubObject (this.{0});\n\n", control_id);
  1519. AddCodeRenderControl (controls.CodeRenderFunction);
  1520. }
  1521. private void ProcessCodeRenderTag ()
  1522. {
  1523. FlushPlainText ();
  1524. CodeRenderTag code_tag = (CodeRenderTag) current;
  1525. controls.UseCodeRender = true;
  1526. if (code_tag.IsVarName)
  1527. controls.CodeRenderFunction.AppendFormat ("\t\t\t__output.Write ({0});\n",
  1528. code_tag.Code);
  1529. else
  1530. controls.CodeRenderFunction.AppendFormat ("\t\t\t{0}\n", code_tag.Code);
  1531. }
  1532. void FlushPlainText ()
  1533. {
  1534. if (textChunk.Length != 0) {
  1535. Element saved = current;
  1536. current = new PlainText (textChunk.ToString ());
  1537. textChunk.Length = 0;
  1538. ProcessPlainText ();
  1539. current = saved;
  1540. }
  1541. }
  1542. void ParseError (string msg, int line, int col)
  1543. {
  1544. throw new ParseException (fullPath, msg, line, col);
  1545. }
  1546. void TagParsed (Tag tag, int line, int col)
  1547. {
  1548. if (waitClosing != null) {
  1549. if (!(tag is CloseTag) || tag.TagID.ToUpper () != waitClosing.ToUpper ())
  1550. throw new HttpException ("Tag " + waitClosing + " not properly closed.");
  1551. waitClosing = null;
  1552. controls.Pop ();
  1553. return;
  1554. }
  1555. if ((sstatus == ScriptStatus.Open || sstatus == ScriptStatus.Text) &&
  1556. tag.TagID.ToUpper () == "SCRIPT" && tag is CloseTag) {
  1557. sstatus = ScriptStatus.Close;
  1558. return;
  1559. }
  1560. current = tag;
  1561. if (current is Directive) {
  1562. ProcessDirective ();
  1563. return;
  1564. } else if (current is DataBindingTag) {
  1565. if (IsApplication)
  1566. throw new ApplicationException (app_file_wrong);
  1567. ProcessDataBindingLiteral ();
  1568. return;
  1569. } else if (current is CodeRenderTag) {
  1570. if (IsApplication)
  1571. throw new ApplicationException (app_file_wrong);
  1572. ProcessCodeRenderTag ();
  1573. return;
  1574. }
  1575. current = Map (tag);
  1576. if (current is ServerObjectTag) {
  1577. ProcessServerObjectTag ();
  1578. return;
  1579. } else if (current is HtmlControlTag) {
  1580. ProcessHtmlControlTag ();
  1581. return;
  1582. }
  1583. if (IsApplication)
  1584. throw new ApplicationException (app_file_wrong);
  1585. if (current is AspComponent) {
  1586. ProcessComponent ();
  1587. } else if (current is CloseTag) {
  1588. ProcessCloseTag ();
  1589. } else if (current is Tag) {
  1590. ProcessHtmlTag ();
  1591. } else {
  1592. throw new HttpException ("This place should not be reached.");
  1593. }
  1594. }
  1595. void TextParsed (string text, int line, int col)
  1596. {
  1597. if (sstatus == ScriptStatus.Open) {
  1598. script.Append (text);
  1599. sstatus = ScriptStatus.Text;
  1600. return;
  1601. }
  1602. textChunk.Append (text);
  1603. }
  1604. public void ProcessElements ()
  1605. {
  1606. AspParser parser = new AspParser (fullPath, File.OpenRead (fullPath));
  1607. parser.Error += new ParseErrorHandler (ParseError);
  1608. parser.TagParsed += new TagParsedHandler (TagParsed);
  1609. parser.TextParsed += new TextParsedHandler (TextParsed);
  1610. try {
  1611. parser.Parse ();
  1612. } catch (CompilationException e) {
  1613. throw;
  1614. } catch (ParseException e) {
  1615. throw;
  1616. } catch (Exception e) {
  1617. throw new ParseException (fullPath, e.Message, parser.Line, parser.Column, e);
  1618. }
  1619. End ();
  1620. parse_ok = true;
  1621. }
  1622. private string GetTemplateDirectory ()
  1623. {
  1624. string templatePath = Path.GetDirectoryName (fullPath);
  1625. string appPath = Path.GetDirectoryName (HttpRuntime.AppDomainAppPath);
  1626. if (templatePath == appPath)
  1627. return "/";
  1628. templatePath = templatePath.Substring (appPath.Length);
  1629. if (Path.DirectorySeparatorChar != '/')
  1630. templatePath = templatePath.Replace (Path.DirectorySeparatorChar, '/');
  1631. return templatePath;
  1632. }
  1633. private void End ()
  1634. {
  1635. FlushPlainText ();
  1636. if (isPage) {
  1637. if (sessionState == SessionState.Enabled || sessionState == SessionState.ReadOnly)
  1638. AddInterface (typeof (System.Web.SessionState.IRequiresSessionState));
  1639. if (sessionState == SessionState.ReadOnly)
  1640. AddInterface (typeof (System.Web.SessionState.IReadOnlySessionState));
  1641. }
  1642. classDecl = "\tpublic class " + className + " : " + parent + interfaces + " {\n";
  1643. prolog.Append ("\n" + classDecl);
  1644. declarations.Append ("\t\tprivate static bool __intialized = false;\n\n");
  1645. if (IsPage)
  1646. declarations.Append ("\t\tprivate static ArrayList __fileDependencies;\n\n");
  1647. // adds the constructor
  1648. constructor.AppendFormat ("\t\tpublic {0} ()\n\t\t{{\n", className);
  1649. if (!IsApplication)
  1650. constructor.Append ("\t\t\tSystem.Collections.ArrayList dependencies;\n\n");
  1651. constructor.AppendFormat ("\t\t\tif (ASP.{0}.__intialized == false){{\n", className);
  1652. if (IsPage) {
  1653. constructor.AppendFormat ("\t\t\t\tdependencies = new System.Collections.ArrayList ();\n" +
  1654. "\t\t\t\tdependencies.Add (@\"{1}\");\n" +
  1655. "\t\t\t\tASP.{0}.__fileDependencies = dependencies;\n",
  1656. className, fullPath);
  1657. }
  1658. constructor.AppendFormat ("\t\t\t\tASP.{0}.__intialized = true;\n\t\t\t}}\n\t\t}}\n\n",
  1659. className);
  1660. if (!IsApplication) {
  1661. //FIXME: add AutoHandlers: don't know what for...yet!
  1662. constructor.AppendFormat (
  1663. "\t\tprotected override int AutoHandlers\n\t\t{{\n" +
  1664. "\t\t\tget {{ return ASP.{0}.__autoHandlers; }}\n" +
  1665. "\t\t\tset {{ ASP.{0}.__autoHandlers = value; }}\n" +
  1666. "\t\t}}\n\n", className);
  1667. constructor.Append (
  1668. "\t\tprotected System.Web.HttpApplication ApplicationInstance\n\t\t{\n" +
  1669. "\t\t\tget { return (System.Web.HttpApplication) this.Context.ApplicationInstance; }\n" +
  1670. "\t\t}\n\n");
  1671. constructor.AppendFormat (
  1672. "\t\tpublic override string TemplateSourceDirectory\n\t\t{{\n" +
  1673. "\t\t\tget {{ return \"{0}\"; }}\n" +
  1674. "\t\t}}\n\n", GetTemplateDirectory ());
  1675. epilog.Append ("\n\t\tprotected override void FrameworkInitialize ()\n\t\t{\n" +
  1676. "\t\t\tthis.__BuildControlTree (this);\n");
  1677. if (IsPage) {
  1678. epilog.AppendFormat ("\t\t\tthis.FileDependencies = ASP.{0}.__fileDependencies;\n" +
  1679. "\t\t\tthis.EnableViewStateMac = true;\n", className);
  1680. }
  1681. epilog.Append ("\t\t}\n\n");
  1682. }
  1683. if (IsPage) {
  1684. Random rnd = new Random ();
  1685. epilog.AppendFormat ("\t\tpublic override int GetTypeHashCode ()\n\t\t{{\n" +
  1686. "\t\t\treturn {0};\n" +
  1687. "\t\t}}\n", rnd.Next ());
  1688. }
  1689. epilog.Append ("\t}\n}\n");
  1690. // Closes the currently opened tags
  1691. StringBuilder old_function = current_function;
  1692. string control_id;
  1693. while (functions.Count > 1){
  1694. old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
  1695. init_funcs.Append (old_function);
  1696. control_id = controls.PeekControlID ();
  1697. FinishControlFunction (control_id);
  1698. controls.AddChild ();
  1699. old_function = (StringBuilder) functions.Pop ();
  1700. current_function = (StringBuilder) functions.Peek ();
  1701. controls.Pop ();
  1702. }
  1703. bool useCodeRender = controls.UseCodeRender;
  1704. if (useCodeRender){
  1705. RemoveLiterals (current_function);
  1706. AddRenderMethodDelegate (current_function, controls.PeekControlID ());
  1707. }
  1708. current_function.Append ("\t\t}\n\n");
  1709. init_funcs.Append (current_function);
  1710. if (useCodeRender)
  1711. AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), controls.PeekControlID ());
  1712. functions.Pop ();
  1713. }
  1714. //
  1715. // Functions related to compilation of user controls
  1716. //
  1717. private static char dirSeparator = Path.DirectorySeparatorChar;
  1718. struct UserControlData
  1719. {
  1720. public UserControlResult result;
  1721. public string className;
  1722. public string assemblyName;
  1723. }
  1724. private static UserControlData GenerateUserControl (string src, HttpContext context)
  1725. {
  1726. UserControlData data = new UserControlData ();
  1727. data.result = UserControlResult.OK;
  1728. UserControlCompiler compiler = new UserControlCompiler (new UserControlParser (src, context));
  1729. Type t = compiler.GetCompiledType ();
  1730. if (t == null) {
  1731. data.result = UserControlResult.CompilationFailed;
  1732. return data;
  1733. }
  1734. data.className = t.Name;
  1735. data.assemblyName = compiler.TargetFile;
  1736. return data;
  1737. }
  1738. }
  1739. }