AspGenerator.cs 60 KB

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