TemplateControlCompiler.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. //
  2. // System.Web.Compilation.TemplateControlCompiler
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.CodeDom;
  31. using System.Collections;
  32. using System.ComponentModel;
  33. using System.Drawing;
  34. using System.Globalization;
  35. using System.Reflection;
  36. using System.Text;
  37. using System.Web;
  38. using System.Web.UI;
  39. namespace System.Web.Compilation
  40. {
  41. class TemplateControlCompiler : BaseCompiler
  42. {
  43. static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
  44. BindingFlags.Instance | BindingFlags.IgnoreCase;
  45. static Type styleType = typeof (System.Web.UI.WebControls.Style);
  46. static Type fontinfoType = typeof (System.Web.UI.WebControls.FontInfo);
  47. TemplateControlParser parser;
  48. int dataBoundAtts;
  49. ILocation currentLocation;
  50. static TypeConverter colorConverter;
  51. static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
  52. static Type [] arrayString = new Type [] {typeof (string)};
  53. static Type [] arrayStringCultureInfo = new Type [] {typeof (string), typeof (CultureInfo)};
  54. public TemplateControlCompiler (TemplateControlParser parser)
  55. : base (parser)
  56. {
  57. this.parser = parser;
  58. }
  59. void EnsureID (ControlBuilder builder)
  60. {
  61. if (builder.ID == null || builder.ID.Trim () == "")
  62. builder.ID = builder.GetNextID (null);
  63. }
  64. void CreateField (ControlBuilder builder, bool check)
  65. {
  66. currentLocation = builder.location;
  67. if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType))
  68. return; // The field or property already exists in a base class and is accesible.
  69. CodeMemberField field;
  70. field = new CodeMemberField (builder.ControlType.FullName, builder.ID);
  71. field.Attributes = MemberAttributes.Family;
  72. mainClass.Members.Add (field);
  73. }
  74. bool CheckBaseFieldOrProperty (string id, Type type)
  75. {
  76. FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);
  77. Type other = null;
  78. if (fld == null || fld.IsPrivate) {
  79. PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
  80. if (prop != null) {
  81. MethodInfo setm = prop.GetSetMethod (true);
  82. if (setm != null)
  83. other = prop.PropertyType;
  84. }
  85. } else {
  86. other = fld.FieldType;
  87. }
  88. if (other == null)
  89. return false;
  90. if (!other.IsAssignableFrom (type)) {
  91. string msg = String.Format ("The base class includes the field '{0}', but its " +
  92. "type '{1}' is not compatible with {2}",
  93. id, other, type);
  94. throw new ParseException (currentLocation, msg);
  95. }
  96. return true;
  97. }
  98. void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr)
  99. {
  100. if (!builder.haveParserVariable) {
  101. CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
  102. p.Name = "__parser";
  103. p.Type = new CodeTypeReference (typeof (IParserAccessor));
  104. p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
  105. builder.method.Statements.Add (p);
  106. builder.haveParserVariable = true;
  107. }
  108. CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
  109. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
  110. invoke.Parameters.Add (expr);
  111. builder.method.Statements.Add (invoke);
  112. }
  113. void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
  114. {
  115. string tailname = ((builder is RootBuilder) ? "Tree" : ("_" + builder.ID));
  116. CodeMemberMethod method = new CodeMemberMethod ();
  117. builder.method = method;
  118. method.Name = "__BuildControl" + tailname;
  119. method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  120. Type type = builder.ControlType;
  121. if (builder.HasAspCode) {
  122. CodeMemberMethod renderMethod = new CodeMemberMethod ();
  123. builder.renderMethod = renderMethod;
  124. renderMethod.Name = "__Render" + tailname;
  125. renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  126. CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
  127. arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
  128. arg1.Name = "__output";
  129. CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
  130. arg2.Type = new CodeTypeReference (typeof (Control));
  131. arg2.Name = "parameterContainer";
  132. renderMethod.Parameters.Add (arg1);
  133. renderMethod.Parameters.Add (arg2);
  134. mainClass.Members.Add (renderMethod);
  135. }
  136. if (childrenAsProperties || builder.ControlType == null) {
  137. string typeString;
  138. if (builder.ControlType != null && builder.isProperty &&
  139. !typeof (ITemplate).IsAssignableFrom (builder.ControlType))
  140. typeString = builder.ControlType.FullName;
  141. else
  142. typeString = "System.Web.UI.Control";
  143. method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
  144. } else {
  145. if (typeof (Control).IsAssignableFrom (type))
  146. method.ReturnType = new CodeTypeReference (typeof (Control));
  147. CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (type);
  148. object [] atts = type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true);
  149. if (atts != null && atts.Length > 0) {
  150. ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
  151. if (att.NeedsTag)
  152. newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
  153. } else if (builder is DataBindingBuilder) {
  154. newExpr.Parameters.Add (new CodePrimitiveExpression (0));
  155. newExpr.Parameters.Add (new CodePrimitiveExpression (1));
  156. }
  157. method.Statements.Add (new CodeVariableDeclarationStatement (builder.ControlType, "__ctrl"));
  158. CodeAssignStatement assign = new CodeAssignStatement ();
  159. assign.Left = ctrlVar;
  160. assign.Right = newExpr;
  161. method.Statements.Add (assign);
  162. CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
  163. builderID.TargetObject = thisRef;
  164. builderID.FieldName = builder.ID;
  165. assign = new CodeAssignStatement ();
  166. assign.Left = builderID;
  167. assign.Right = ctrlVar;
  168. method.Statements.Add (assign);
  169. if (typeof (UserControl).IsAssignableFrom (type)) {
  170. CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
  171. mref.TargetObject = builderID;
  172. mref.MethodName = "InitializeAsUserControl";
  173. CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
  174. initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
  175. method.Statements.Add (initAsControl);
  176. }
  177. }
  178. mainClass.Members.Add (method);
  179. }
  180. void AddLiteralSubObject (ControlBuilder builder, string str)
  181. {
  182. if (!builder.HasAspCode) {
  183. CodeObjectCreateExpression expr;
  184. expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
  185. AddParsedSubObjectStmt (builder, expr);
  186. } else {
  187. CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
  188. methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
  189. methodRef.MethodName = "Write";
  190. CodeMethodInvokeExpression expr;
  191. expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
  192. builder.renderMethod.Statements.Add (expr);
  193. }
  194. }
  195. string TrimDB (string value)
  196. {
  197. string str = value.Trim ();
  198. str = str.Substring (3);
  199. return str.Substring (0, str.Length - 2);
  200. }
  201. string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
  202. {
  203. value = TrimDB (value);
  204. CodeMemberMethod method;
  205. string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
  206. method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
  207. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  208. // This should be a CodePropertyReferenceExpression for properties... but it works anyway
  209. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
  210. CodeExpression expr;
  211. if (type == typeof (string)) {
  212. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  213. CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
  214. tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
  215. tostring.Parameters.Add (new CodeSnippetExpression (value));
  216. expr = tostring;
  217. } else {
  218. CodeSnippetExpression snippet = new CodeSnippetExpression (value);
  219. expr = new CodeCastExpression (type, snippet);
  220. }
  221. method.Statements.Add (new CodeAssignStatement (field, expr));
  222. mainClass.Members.Add (method);
  223. return method.Name;
  224. }
  225. void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, bool isDataBound)
  226. {
  227. CodeMemberMethod method = builder.method;
  228. if (isDataBound) {
  229. string dbMethodName = DataBoundProperty (builder, type, var_name, att);
  230. AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
  231. return;
  232. }
  233. CodeAssignStatement assign = new CodeAssignStatement ();
  234. assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
  235. currentLocation = builder.location;
  236. assign.Right = GetExpressionFromString (type, att);
  237. method.Statements.Add (assign);
  238. }
  239. bool IsDataBound (string value)
  240. {
  241. if (value == null || value == "")
  242. return false;
  243. string str = value.Trim ();
  244. return (str.StartsWith ("<%#") && str.EndsWith ("%>"));
  245. }
  246. bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id, string attValue)
  247. {
  248. CodeMemberMethod method = builder.method;
  249. int hyphen = id.IndexOf ('-');
  250. bool isPropertyInfo = (member is PropertyInfo);
  251. bool is_processed = false;
  252. bool isDataBound = IsDataBound (attValue);
  253. Type type;
  254. if (isPropertyInfo) {
  255. type = ((PropertyInfo) member).PropertyType;
  256. if (hyphen == -1 && ((PropertyInfo) member).CanWrite == false)
  257. return false;
  258. } else {
  259. type = ((FieldInfo) member).FieldType;
  260. }
  261. if (0 == String.Compare (member.Name, id, true)){
  262. AddCodeForPropertyOrField (builder, type, member.Name, attValue, isDataBound);
  263. return true;
  264. }
  265. if (hyphen == -1)
  266. return false;
  267. string prop_field = id.Replace ("-", ".");
  268. string [] parts = prop_field.Split (new char [] {'.'});
  269. if (parts.Length != 2 || 0 != String.Compare (member.Name, parts [0], true))
  270. return false;
  271. PropertyInfo [] subprops = type.GetProperties ();
  272. foreach (PropertyInfo subprop in subprops) {
  273. if (0 != String.Compare (subprop.Name, parts [1], true))
  274. continue;
  275. if (subprop.CanWrite == false)
  276. return false;
  277. bool is_bool = subprop.PropertyType == typeof (bool);
  278. if (!is_bool && attValue == null)
  279. return false; // Font-Size -> Font-Size="" as html
  280. string value;
  281. if (attValue == null && is_bool)
  282. value = "true"; // Font-Bold <=> Font-Bold="true"
  283. else
  284. value = attValue;
  285. AddCodeForPropertyOrField (builder, subprop.PropertyType,
  286. member.Name + "." + subprop.Name,
  287. value, isDataBound);
  288. is_processed = true;
  289. }
  290. return is_processed;
  291. }
  292. void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
  293. {
  294. //"__ctrl.{0} += new {1} (this.{2});"
  295. CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
  296. CodeDelegateCreateExpression create;
  297. create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
  298. CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
  299. method.Statements.Add (attach);
  300. }
  301. void CreateAssignStatementsFromAttributes (ControlBuilder builder)
  302. {
  303. this.dataBoundAtts = 0;
  304. IDictionary atts = builder.attribs;
  305. if (atts == null || atts.Count == 0)
  306. return;
  307. EventInfo [] ev_info = null;
  308. PropertyInfo [] prop_info = null;
  309. FieldInfo [] field_info = null;
  310. bool is_processed = false;
  311. Type type = builder.ControlType;
  312. foreach (string id in atts.Keys){
  313. if (0 == String.Compare (id, "runat", true))
  314. continue;
  315. is_processed = false;
  316. string attvalue = atts [id] as string;
  317. if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
  318. if (ev_info == null)
  319. ev_info = type.GetEvents ();
  320. string id_as_event = id.Substring (2);
  321. foreach (EventInfo ev in ev_info){
  322. if (0 == String.Compare (ev.Name, id_as_event, true)){
  323. AddEventAssign (builder.method,
  324. ev.Name,
  325. ev.EventHandlerType,
  326. attvalue);
  327. is_processed = true;
  328. break;
  329. }
  330. }
  331. if (is_processed)
  332. continue;
  333. }
  334. if (prop_info == null)
  335. prop_info = type.GetProperties ();
  336. foreach (PropertyInfo prop in prop_info) {
  337. is_processed = ProcessPropertiesAndFields (builder, prop, id, attvalue);
  338. if (is_processed)
  339. break;
  340. }
  341. if (is_processed)
  342. continue;
  343. if (field_info == null)
  344. field_info = type.GetFields ();
  345. foreach (FieldInfo field in field_info){
  346. is_processed = ProcessPropertiesAndFields (builder, field, id, attvalue);
  347. if (is_processed)
  348. break;
  349. }
  350. if (is_processed)
  351. continue;
  352. if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
  353. throw new ParseException (builder.location, "Unrecognized attribute: " + id);
  354. CodeCastExpression cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
  355. CodeMethodReferenceExpression methodExpr;
  356. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  357. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr);
  358. expr.Parameters.Add (new CodePrimitiveExpression (id));
  359. expr.Parameters.Add (new CodePrimitiveExpression ((string) atts [id]));
  360. builder.method.Statements.Add (expr);
  361. }
  362. }
  363. void AddRenderControl (ControlBuilder builder)
  364. {
  365. CodeIndexerExpression indexer = new CodeIndexerExpression ();
  366. indexer.TargetObject = new CodePropertyReferenceExpression (
  367. new CodeArgumentReferenceExpression ("parameterContainer"),
  368. "Controls");
  369. indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
  370. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
  371. invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
  372. builder.renderMethod.Statements.Add (invoke);
  373. builder.renderIndex++;
  374. }
  375. void AddChildCall (ControlBuilder parent, ControlBuilder child)
  376. {
  377. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
  378. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
  379. object [] atts = child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
  380. if (atts != null && atts.Length > 0) {
  381. PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
  382. CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
  383. CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
  384. build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
  385. build.Parameters.Add (new CodePrimitiveExpression (child.ID));
  386. #if NET_1_1
  387. if (pca.Shared)
  388. build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
  389. else
  390. #endif
  391. build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
  392. build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
  393. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
  394. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
  395. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
  396. build.Parameters.Add (new CodeDelegateCreateExpression (
  397. new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
  398. thisRef, child.method.Name));
  399. parent.method.Statements.Add (build);
  400. if (parent.HasAspCode)
  401. AddRenderControl (parent);
  402. return;
  403. }
  404. if (child.isProperty || parent.ChildrenAsProperties) {
  405. expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
  406. parent.method.Statements.Add (expr);
  407. return;
  408. }
  409. parent.method.Statements.Add (expr);
  410. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
  411. if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
  412. AddParsedSubObjectStmt (parent, field);
  413. } else {
  414. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
  415. invoke.Parameters.Add (field);
  416. parent.method.Statements.Add (invoke);
  417. }
  418. if (parent.HasAspCode)
  419. AddRenderControl (parent);
  420. }
  421. void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
  422. {
  423. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  424. CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
  425. newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
  426. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  427. newCompiled.Parameters.Add (newBuild);
  428. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  429. method.Statements.Add (assign);
  430. }
  431. void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
  432. {
  433. if (cr.Code == null || cr.Code.Trim () == "")
  434. return;
  435. if (!cr.IsAssign) {
  436. CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
  437. parent.renderMethod.Statements.Add (code);
  438. return;
  439. }
  440. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
  441. expr.Method = new CodeMethodReferenceExpression (
  442. new CodeArgumentReferenceExpression ("__output"),
  443. "Write");
  444. expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
  445. parent.renderMethod.Statements.Add (expr);
  446. }
  447. static Type GetContainerType (ControlBuilder builder)
  448. {
  449. Type type = builder.NamingContainerType;
  450. PropertyInfo prop = type.GetProperty ("Items", noCaseFlags);
  451. if (prop == null)
  452. return type;
  453. Type ptype = prop.PropertyType;
  454. if (!typeof (ICollection).IsAssignableFrom (ptype))
  455. return type;
  456. prop = ptype.GetProperty ("Item", noCaseFlags);
  457. if (prop == null)
  458. return type;
  459. return prop.PropertyType;
  460. }
  461. CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
  462. {
  463. CodeMemberMethod method = new CodeMemberMethod ();
  464. method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  465. method.Name = name;
  466. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
  467. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
  468. CodeTypeReference containerRef = new CodeTypeReference (container);
  469. CodeTypeReference targetRef = new CodeTypeReference (target);
  470. CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
  471. decl.Name = "Container";
  472. decl.Type = containerRef;
  473. method.Statements.Add (decl);
  474. decl = new CodeVariableDeclarationStatement();
  475. decl.Name = "target";
  476. decl.Type = targetRef;
  477. method.Statements.Add (decl);
  478. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  479. CodeAssignStatement assign = new CodeAssignStatement ();
  480. assign.Left = targetExpr;
  481. assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
  482. method.Statements.Add (assign);
  483. assign = new CodeAssignStatement ();
  484. assign.Left = new CodeVariableReferenceExpression ("Container");
  485. assign.Right = new CodeCastExpression (containerRef,
  486. new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
  487. method.Statements.Add (assign);
  488. return method;
  489. }
  490. void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
  491. {
  492. if (db.Code == null || db.Code.Trim () == "")
  493. return;
  494. EnsureID (db);
  495. CreateField (db, false);
  496. string dbMethodName = "__DataBind_" + db.ID;
  497. // Add the method that builds the DataBoundLiteralControl
  498. InitMethod (db, false, false);
  499. CodeMemberMethod method = db.method;
  500. AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
  501. method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  502. // Add the DataBind handler
  503. method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
  504. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  505. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  506. invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
  507. invoke.Parameters.Add (new CodePrimitiveExpression (0));
  508. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  509. tostring.Method = new CodeMethodReferenceExpression (
  510. new CodeTypeReferenceExpression (typeof (Convert)),
  511. "ToString");
  512. tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
  513. invoke.Parameters.Add (tostring);
  514. method.Statements.Add (invoke);
  515. mainClass.Members.Add (method);
  516. AddChildCall (builder, db);
  517. }
  518. void FlushText (ControlBuilder builder, StringBuilder sb)
  519. {
  520. if (sb.Length > 0) {
  521. AddLiteralSubObject (builder, sb.ToString ());
  522. sb.Length = 0;
  523. }
  524. }
  525. void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
  526. {
  527. EnsureID (builder);
  528. bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
  529. if (!isTemplate && !inTemplate) {
  530. CreateField (builder, true);
  531. } else if (!isTemplate) {
  532. builder.ID = builder.GetNextID (null);
  533. CreateField (builder, false);
  534. }
  535. InitMethod (builder, isTemplate, childrenAsProperties);
  536. if (builder.GetType () != typeof (TemplateBuilder))
  537. CreateAssignStatementsFromAttributes (builder);
  538. if (builder.Children != null && builder.Children.Count > 0) {
  539. ArrayList templates = null;
  540. StringBuilder sb = new StringBuilder ();
  541. foreach (object b in builder.Children) {
  542. if (b is string) {
  543. sb.Append ((string) b);
  544. continue;
  545. }
  546. FlushText (builder, sb);
  547. if (b is ObjectTagBuilder) {
  548. ProcessObjectTag ((ObjectTagBuilder) b);
  549. continue;
  550. }
  551. if (b is TemplateBuilder) {
  552. if (templates == null)
  553. templates = new ArrayList ();
  554. templates.Add (b);
  555. continue;
  556. }
  557. if (b is CodeRenderBuilder) {
  558. AddCodeRender (builder, (CodeRenderBuilder) b);
  559. continue;
  560. }
  561. if (b is DataBindingBuilder) {
  562. AddDataBindingLiteral (builder, (DataBindingBuilder) b);
  563. continue;
  564. }
  565. if (b is ControlBuilder) {
  566. ControlBuilder child = (ControlBuilder) b;
  567. CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
  568. AddChildCall (builder, child);
  569. continue;
  570. }
  571. throw new Exception ("???");
  572. }
  573. FlushText (builder, sb);
  574. if (templates != null) {
  575. foreach (ControlBuilder b in templates) {
  576. CreateControlTree (b, true, false);
  577. AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
  578. }
  579. }
  580. }
  581. if (builder.defaultPropertyBuilder != null) {
  582. ControlBuilder b = builder.defaultPropertyBuilder;
  583. CreateControlTree (b, false, true);
  584. AddChildCall (builder, b);
  585. }
  586. if (builder.HasAspCode) {
  587. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  588. m.TargetObject = thisRef;
  589. m.MethodName = builder.renderMethod.Name;
  590. CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
  591. create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
  592. create.TargetObject = thisRef;
  593. create.MethodName = builder.renderMethod.Name;
  594. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  595. invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
  596. invoke.Parameters.Add (create);
  597. builder.method.Statements.Add (invoke);
  598. }
  599. if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
  600. builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  601. }
  602. protected override void CreateMethods ()
  603. {
  604. base.CreateMethods ();
  605. CreateProperties ();
  606. CreateControlTree (parser.RootBuilder, false, false);
  607. CreateFrameworkInitializeMethod ();
  608. }
  609. void CreateFrameworkInitializeMethod ()
  610. {
  611. CodeMemberMethod method = new CodeMemberMethod ();
  612. method.Name = "FrameworkInitialize";
  613. method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  614. AddStatementsToFrameworkInitialize (method);
  615. mainClass.Members.Add (method);
  616. }
  617. protected virtual void AddStatementsToFrameworkInitialize (CodeMemberMethod method)
  618. {
  619. if (!parser.EnableViewState) {
  620. CodeAssignStatement stmt = new CodeAssignStatement ();
  621. stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
  622. stmt.Right = new CodePrimitiveExpression (false);
  623. method.Statements.Add (stmt);
  624. }
  625. CodeMethodReferenceExpression methodExpr;
  626. methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
  627. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
  628. method.Statements.Add (new CodeExpressionStatement (expr));
  629. }
  630. protected override void AddApplicationAndSessionObjects ()
  631. {
  632. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
  633. CreateFieldForObject (tag.Type, tag.ObjectID);
  634. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
  635. }
  636. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
  637. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
  638. }
  639. }
  640. protected void ProcessObjectTag (ObjectTagBuilder tag)
  641. {
  642. string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
  643. CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
  644. }
  645. void CreateProperties ()
  646. {
  647. if (!parser.AutoEventWireup) {
  648. CreateAutoEventWireup ();
  649. } else {
  650. CreateAutoHandlers ();
  651. }
  652. CreateApplicationInstance ();
  653. CreateTemplateSourceDirectory ();
  654. }
  655. void CreateTemplateSourceDirectory ()
  656. {
  657. CodeMemberProperty prop = new CodeMemberProperty ();
  658. prop.Type = new CodeTypeReference (typeof (string));
  659. prop.Name = "TemplateSourceDirectory";
  660. prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
  661. CodePrimitiveExpression expr = new CodePrimitiveExpression (parser.BaseVirtualDir);
  662. prop.GetStatements.Add (new CodeMethodReturnStatement (expr));
  663. mainClass.Members.Add (prop);
  664. }
  665. void CreateApplicationInstance ()
  666. {
  667. CodeMemberProperty prop = new CodeMemberProperty ();
  668. Type appType = typeof (HttpApplication);
  669. prop.Type = new CodeTypeReference (appType);
  670. prop.Name = "ApplicationInstance";
  671. prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
  672. CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
  673. propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
  674. CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
  675. prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
  676. mainClass.Members.Add (prop);
  677. }
  678. void CreateAutoHandlers ()
  679. {
  680. // Create AutoHandlers property
  681. CodeMemberProperty prop = new CodeMemberProperty ();
  682. prop.Type = new CodeTypeReference (typeof (int));
  683. prop.Name = "AutoHandlers";
  684. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  685. CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
  686. CodeFieldReferenceExpression fldRef ;
  687. fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
  688. ret.Expression = fldRef;
  689. prop.GetStatements.Add (ret);
  690. prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
  691. mainClass.Members.Add (prop);
  692. // Add the __autoHandlers field
  693. CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
  694. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  695. mainClass.Members.Add (fld);
  696. }
  697. void CreateAutoEventWireup ()
  698. {
  699. // The getter returns false
  700. CodeMemberProperty prop = new CodeMemberProperty ();
  701. prop.Type = new CodeTypeReference (typeof (bool));
  702. prop.Name = "SupportAutoEvents";
  703. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  704. prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
  705. mainClass.Members.Add (prop);
  706. }
  707. CodeExpression GetExpressionFromString (Type type, string str)
  708. {
  709. if (type == typeof (string))
  710. return new CodePrimitiveExpression (str);
  711. if (type == typeof (bool)) {
  712. if (str == null || str == "" || 0 == String.Compare (str, "true", true))
  713. return new CodePrimitiveExpression (true);
  714. else if (0 == String.Compare (str, "false", true))
  715. return new CodePrimitiveExpression (false);
  716. else
  717. throw new ParseException (currentLocation,
  718. "Value '" + str + "' is not a valid boolean.");
  719. }
  720. if (str == null)
  721. return new CodePrimitiveExpression (null);
  722. if (type.IsPrimitive)
  723. return new CodePrimitiveExpression (Convert.ChangeType (str, type));
  724. if (type.IsEnum) {
  725. object val = null;
  726. try {
  727. val = Enum.Parse (type, str, true);
  728. } catch (Exception) {
  729. throw new ParseException (currentLocation,
  730. str + " is not a valid value for enum '" + type + "'");
  731. }
  732. CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
  733. expr.TargetObject = new CodeTypeReferenceExpression (type);
  734. expr.FieldName = val.ToString ();
  735. return expr;
  736. }
  737. if (type == typeof (string [])) {
  738. string [] subs = str.Split (',');
  739. CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
  740. expr.CreateType = new CodeTypeReference (typeof (string));
  741. foreach (string v in subs) {
  742. expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
  743. }
  744. return expr;
  745. }
  746. if (type == typeof (Size)) {
  747. string [] subs = str.Split (',');
  748. if (subs.Length != 2)
  749. throw new ParseException (currentLocation,
  750. String.Format ("Cannot create {0} from '{1}'", type, str));
  751. int width = 0;
  752. int height = 0;
  753. try {
  754. width = Int32.Parse (subs [0]);
  755. height = Int32.Parse (subs [0]);
  756. new Size (width, height);
  757. } catch {
  758. throw new ParseException (currentLocation,
  759. String.Format ("Cannot create {0} from '{1}'", type, str));
  760. }
  761. CodeObjectCreateExpression expr = new CodeObjectCreateExpression ();
  762. expr.CreateType = new CodeTypeReference (type);
  763. expr.Parameters.Add (new CodePrimitiveExpression (width));
  764. expr.Parameters.Add (new CodePrimitiveExpression (height));
  765. return expr;
  766. }
  767. if (type == typeof (Color)){
  768. if (colorConverter == null)
  769. colorConverter = TypeDescriptor.GetConverter (typeof (Color));
  770. Color c;
  771. try {
  772. if (str.IndexOf (',') == -1) {
  773. c = (Color) colorConverter.ConvertFromString (str);
  774. } else {
  775. int [] argb = new int [4];
  776. argb [0] = 255;
  777. string [] parts = str.Split (',');
  778. int length = parts.Length;
  779. if (length < 3)
  780. throw new Exception ();
  781. int basei = (length == 4) ? 0 : 1;
  782. for (int i = length - 1; i >= 0; i--) {
  783. argb [basei + i] = (int) Byte.Parse (parts [i]);
  784. }
  785. c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
  786. }
  787. } catch (Exception e){
  788. throw new ParseException (currentLocation,
  789. "Color " + str + " is not a valid color.", e);
  790. }
  791. if (c.IsKnownColor){
  792. CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
  793. if (c.IsSystemColor)
  794. type = typeof (SystemColors);
  795. expr.TargetObject = new CodeTypeReferenceExpression (type);
  796. expr.FieldName = c.Name;
  797. return expr;
  798. } else {
  799. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  800. m.TargetObject = new CodeTypeReferenceExpression (type);
  801. m.MethodName = "FromArgb";
  802. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  803. invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
  804. invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
  805. invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
  806. invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
  807. return invoke;
  808. }
  809. }
  810. TypeConverter converter = TypeDescriptor.GetConverter (type);
  811. if (converter != null && converter.CanConvertFrom (typeof (string))) {
  812. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  813. m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
  814. m.MethodName = "GetConverter";
  815. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  816. CodeTypeReference tref = new CodeTypeReference (type);
  817. invoke.Parameters.Add (new CodeTypeOfExpression (tref));
  818. invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
  819. invoke.Parameters.Add (new CodePrimitiveExpression (str));
  820. return new CodeCastExpression (tref, invoke);
  821. }
  822. bool parms = false;
  823. BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
  824. MethodInfo parse = type.GetMethod ("Parse", flags, null, arrayStringCultureInfo, null);
  825. if (parse != null) {
  826. parms = true;
  827. } else {
  828. parse = type.GetMethod ("Parse", flags, null, arrayString, null);
  829. }
  830. if (parse != null) {
  831. object o = null;
  832. try {
  833. if (parms)
  834. o = parse.Invoke (null, new object [] { str, CultureInfo.InvariantCulture });
  835. else
  836. o = parse.Invoke (null, new object [] { str });
  837. } catch (Exception e) {
  838. throw new ParseException (currentLocation, "Cannot parse " + str + " as " + type, e);
  839. }
  840. if (o == null)
  841. throw new ParseException (currentLocation, str + " as " + type + " is null");
  842. CodeTypeReferenceExpression exprType = new CodeTypeReferenceExpression (type);
  843. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (exprType, "Parse");
  844. //FIXME: may be we gotta ensure roundtrip between o.ToString and Parse
  845. invoke.Parameters.Add (new CodePrimitiveExpression (o.ToString ()));
  846. if (parms) {
  847. CodeTypeReferenceExpression texp = new CodeTypeReferenceExpression (typeof (CultureInfo));
  848. CodePropertyReferenceExpression pexp = new CodePropertyReferenceExpression ();
  849. pexp.TargetObject = texp;
  850. pexp.PropertyName = "InvariantCulture";
  851. invoke.Parameters.Add (pexp);
  852. }
  853. return invoke;
  854. }
  855. // FIXME: Arrays
  856. Console.WriteLine ("Unknown type: " + type + " value: " + str);
  857. return new CodePrimitiveExpression (str);
  858. }
  859. }
  860. }