2
0

TemplateControlCompiler.cs 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  1. //
  2. // System.Web.Compilation.TemplateControlCompiler
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. // Marek Habersack ([email protected])
  7. //
  8. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  9. // (C) 2004-2008 Novell, Inc (http://novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.CodeDom;
  32. using System.Collections;
  33. using System.ComponentModel;
  34. using System.Drawing;
  35. using System.Globalization;
  36. using System.Reflection;
  37. using System.Text;
  38. using System.Web;
  39. using System.Web.UI;
  40. using System.Web.UI.WebControls;
  41. using System.Web.Util;
  42. using System.ComponentModel.Design.Serialization;
  43. using System.Text.RegularExpressions;
  44. #if NET_2_0
  45. using System.Configuration;
  46. using System.Collections.Specialized;
  47. using System.Collections.Generic;
  48. using System.Web.Configuration;
  49. #endif
  50. namespace System.Web.Compilation
  51. {
  52. class TemplateControlCompiler : BaseCompiler
  53. {
  54. static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
  55. BindingFlags.Instance | BindingFlags.IgnoreCase;
  56. static Type monoTypeType = Type.GetType ("System.MonoType");
  57. TemplateControlParser parser;
  58. int dataBoundAtts;
  59. internal ILocation currentLocation;
  60. static TypeConverter colorConverter;
  61. internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
  62. #if NET_2_0
  63. static Regex bindRegex = new Regex (@"Bind\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)\s*%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  64. static Regex bindRegexInValue = new Regex (@"Bind\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  65. #endif
  66. static Regex evalRegexInValue = new Regex (@"Eval\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  67. public TemplateControlCompiler (TemplateControlParser parser)
  68. : base (parser)
  69. {
  70. this.parser = parser;
  71. }
  72. protected void EnsureID (ControlBuilder builder)
  73. {
  74. if (builder.ID == null || builder.ID.Trim () == "")
  75. builder.ID = builder.GetNextID (null);
  76. }
  77. void CreateField (ControlBuilder builder, bool check)
  78. {
  79. if (builder == null || builder.ID == null || builder.ControlType == null)
  80. return;
  81. #if NET_2_0
  82. if (partialNameOverride [builder.ID] != null)
  83. return;
  84. #endif
  85. MemberAttributes ma = MemberAttributes.Family;
  86. currentLocation = builder.location;
  87. if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType, ref ma))
  88. return; // The field or property already exists in a base class and is accesible.
  89. CodeMemberField field;
  90. field = new CodeMemberField (builder.ControlType.FullName, builder.ID);
  91. field.Attributes = ma;
  92. #if NET_2_0
  93. field.Type.Options |= CodeTypeReferenceOptions.GlobalReference;
  94. if (partialClass != null)
  95. partialClass.Members.Add (AddLinePragma (field, builder));
  96. else
  97. #endif
  98. mainClass.Members.Add (AddLinePragma (field, builder));
  99. }
  100. bool CheckBaseFieldOrProperty (string id, Type type, ref MemberAttributes ma)
  101. {
  102. FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);
  103. Type other = null;
  104. if (fld == null || fld.IsPrivate) {
  105. PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
  106. if (prop != null) {
  107. MethodInfo setm = prop.GetSetMethod (true);
  108. if (setm != null)
  109. other = prop.PropertyType;
  110. }
  111. } else {
  112. other = fld.FieldType;
  113. }
  114. if (other == null)
  115. return false;
  116. if (!other.IsAssignableFrom (type)) {
  117. #if NET_2_0
  118. ma |= MemberAttributes.New;
  119. return false;
  120. #else
  121. string msg = String.Format ("The base class includes the field '{0}', but its " +
  122. "type '{1}' is not compatible with {2}",
  123. id, other, type);
  124. throw new ParseException (currentLocation, msg);
  125. #endif
  126. }
  127. return true;
  128. }
  129. void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr)
  130. {
  131. if (!builder.haveParserVariable) {
  132. CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
  133. p.Name = "__parser";
  134. p.Type = new CodeTypeReference (typeof (IParserAccessor));
  135. p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
  136. builder.methodStatements.Add (p);
  137. builder.haveParserVariable = true;
  138. }
  139. CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
  140. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
  141. invoke.Parameters.Add (expr);
  142. builder.methodStatements.Add (AddLinePragma (invoke, builder));
  143. }
  144. void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
  145. {
  146. currentLocation = builder.location;
  147. string tailname = ((builder is RootBuilder) ? "Tree" : ("_" + builder.ID));
  148. CodeMemberMethod method = new CodeMemberMethod ();
  149. builder.method = method;
  150. builder.methodStatements = method.Statements;
  151. method.Name = "__BuildControl" + tailname;
  152. method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  153. Type type = builder.ControlType;
  154. /* in the case this is the __BuildControlTree
  155. * method, allow subclasses to insert control
  156. * specific code. */
  157. if (builder is RootBuilder) {
  158. #if NET_2_0
  159. SetCustomAttributes (method);
  160. #endif
  161. AddStatementsToInitMethod (method);
  162. }
  163. if (builder.HasAspCode) {
  164. CodeMemberMethod renderMethod = new CodeMemberMethod ();
  165. builder.renderMethod = renderMethod;
  166. renderMethod.Name = "__Render" + tailname;
  167. renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  168. CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
  169. arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
  170. arg1.Name = "__output";
  171. CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
  172. arg2.Type = new CodeTypeReference (typeof (Control));
  173. arg2.Name = "parameterContainer";
  174. renderMethod.Parameters.Add (arg1);
  175. renderMethod.Parameters.Add (arg2);
  176. mainClass.Members.Add (renderMethod);
  177. }
  178. if (childrenAsProperties || builder.ControlType == null) {
  179. string typeString;
  180. if (builder is RootBuilder)
  181. typeString = parser.ClassName;
  182. else {
  183. if (builder.ControlType != null && builder.isProperty &&
  184. !typeof (ITemplate).IsAssignableFrom (builder.ControlType))
  185. typeString = builder.ControlType.FullName;
  186. else
  187. typeString = "System.Web.UI.Control";
  188. ProcessTemplateChildren (builder);
  189. }
  190. method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
  191. } else {
  192. if (typeof (Control).IsAssignableFrom (type))
  193. method.ReturnType = new CodeTypeReference (typeof (Control));
  194. // _ctrl = new $controlType ($parameters);
  195. //
  196. CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (type);
  197. object [] atts = type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true);
  198. if (atts != null && atts.Length > 0) {
  199. ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
  200. if (att.NeedsTag)
  201. newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
  202. } else if (builder is DataBindingBuilder) {
  203. newExpr.Parameters.Add (new CodePrimitiveExpression (0));
  204. newExpr.Parameters.Add (new CodePrimitiveExpression (1));
  205. }
  206. method.Statements.Add (new CodeVariableDeclarationStatement (builder.ControlType, "__ctrl"));
  207. CodeAssignStatement assign = new CodeAssignStatement ();
  208. assign.Left = ctrlVar;
  209. assign.Right = newExpr;
  210. method.Statements.Add (AddLinePragma (assign, builder));
  211. // this.$builderID = _ctrl;
  212. //
  213. CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
  214. builderID.TargetObject = thisRef;
  215. builderID.FieldName = builder.ID;
  216. assign = new CodeAssignStatement ();
  217. assign.Left = builderID;
  218. assign.Right = ctrlVar;
  219. method.Statements.Add (AddLinePragma (assign, builder));
  220. if (typeof (UserControl).IsAssignableFrom (type)) {
  221. CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
  222. mref.TargetObject = builderID;
  223. mref.MethodName = "InitializeAsUserControl";
  224. CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
  225. initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
  226. method.Statements.Add (initAsControl);
  227. }
  228. #if NET_2_0
  229. if (builder.ParentTemplateBuilder is System.Web.UI.WebControls.ContentBuilderInternal) {
  230. PropertyInfo pi;
  231. try {
  232. pi = type.GetProperty ("TemplateControl");
  233. } catch (Exception) {
  234. pi = null;
  235. }
  236. if (pi != null && pi.CanWrite) {
  237. // __ctrl.TemplateControl = this;
  238. assign = new CodeAssignStatement ();
  239. assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
  240. assign.Right = thisRef;
  241. method.Statements.Add (assign);
  242. }
  243. }
  244. // _ctrl.SkinID = $value
  245. // _ctrl.ApplyStyleSheetSkin (this);
  246. //
  247. // the SkinID assignment needs to come
  248. // before the call to
  249. // ApplyStyleSheetSkin, for obvious
  250. // reasons. We skip SkinID in
  251. // CreateAssignStatementsFromAttributes
  252. // below.
  253. //
  254. if (builder.attribs != null) {
  255. string skinid = builder.attribs ["skinid"] as string;
  256. if (skinid != null)
  257. CreateAssignStatementFromAttribute (builder, "skinid");
  258. }
  259. if (typeof (WebControl).IsAssignableFrom (type)) {
  260. CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
  261. if (typeof (Page).IsAssignableFrom (parser.BaseType))
  262. applyStyleSheetSkin.Parameters.Add (thisRef);
  263. else
  264. applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
  265. method.Statements.Add (applyStyleSheetSkin);
  266. }
  267. #endif
  268. // Process template children before anything else
  269. ProcessTemplateChildren (builder);
  270. // process ID here. It should be set before any other attributes are
  271. // assigned, since the control code may rely on ID being set. We
  272. // skip ID in CreateAssignStatementsFromAttributes
  273. if (builder.attribs != null) {
  274. string ctl_id = builder.attribs ["id"] as string;
  275. if (ctl_id != null && ctl_id != String.Empty)
  276. CreateAssignStatementFromAttribute (builder, "id");
  277. }
  278. #if NET_2_0
  279. if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
  280. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (thisRef, "ContentPlaceHolders");
  281. CodeMethodInvokeExpression addPlaceholder = new CodeMethodInvokeExpression (prop, "Add");
  282. addPlaceholder.Parameters.Add (ctrlVar);
  283. method.Statements.Add (addPlaceholder);
  284. CodeConditionStatement condStatement;
  285. // Add the __Template_* field
  286. CodeMemberField fld = new CodeMemberField (typeof (ITemplate), "__Template_" + builder.ID);
  287. fld.Attributes = MemberAttributes.Private;
  288. mainClass.Members.Add (fld);
  289. CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
  290. templateID.TargetObject = thisRef;
  291. templateID.FieldName = "__Template_" + builder.ID;
  292. // if ((this.ContentTemplates != null)) {
  293. // this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
  294. // }
  295. //
  296. CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
  297. contentTemplates.TargetObject = thisRef;
  298. contentTemplates.FieldName = "ContentTemplates";
  299. CodeIndexerExpression indexer = new CodeIndexerExpression ();
  300. indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
  301. indexer.Indices.Add (new CodePrimitiveExpression (builder.ID));
  302. assign = new CodeAssignStatement ();
  303. assign.Left = templateID;
  304. assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);
  305. condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
  306. CodeBinaryOperatorType.IdentityInequality,
  307. new CodePrimitiveExpression (null)),
  308. assign);
  309. method.Statements.Add (condStatement);
  310. // if ((this.__Template_mainContent != null)) {
  311. // this.__Template_mainContent.InstantiateIn(__ctrl);
  312. // }
  313. // and also set things up such that any additional code ends up in:
  314. // else {
  315. // ...
  316. // }
  317. //
  318. CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
  319. methodRef.TargetObject = templateID;
  320. methodRef.MethodName = "InstantiateIn";
  321. CodeMethodInvokeExpression instantiateInInvoke;
  322. instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);
  323. condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
  324. CodeBinaryOperatorType.IdentityInequality,
  325. new CodePrimitiveExpression (null)),
  326. new CodeExpressionStatement (instantiateInInvoke));
  327. method.Statements.Add (condStatement);
  328. // this is the bit that causes the following stuff to end up in the else { }
  329. builder.methodStatements = condStatement.FalseStatements;
  330. }
  331. #endif
  332. }
  333. mainClass.Members.Add (method);
  334. }
  335. void ProcessTemplateChildren (ControlBuilder builder)
  336. {
  337. ArrayList templates = builder.TemplateChildren;
  338. if (templates != null && templates.Count > 0) {
  339. foreach (TemplateBuilder tb in templates) {
  340. CreateControlTree (tb, true, false);
  341. #if NET_2_0
  342. if (tb.BindingDirection == BindingDirection.TwoWay) {
  343. string extractMethod = CreateExtractValuesMethod (tb);
  344. AddBindableTemplateInvocation (builder, tb.TagName, tb.method.Name, extractMethod);
  345. } else
  346. #endif
  347. AddTemplateInvocation (builder, tb.TagName, tb.method.Name);
  348. }
  349. }
  350. }
  351. #if NET_2_0
  352. void SetCustomAttribute (CodeMemberMethod method, UnknownAttributeDescriptor uad)
  353. {
  354. CodeAssignStatement assign = new CodeAssignStatement ();
  355. assign.Left = new CodePropertyReferenceExpression (
  356. new CodeArgumentReferenceExpression("__ctrl"),
  357. uad.Info.Name);
  358. assign.Right = GetExpressionFromString (uad.Value.GetType (), uad.Value.ToString (), uad.Info);
  359. method.Statements.Add (assign);
  360. }
  361. void SetCustomAttributes (CodeMemberMethod method)
  362. {
  363. Type baseType = parser.BaseType;
  364. if (baseType == null)
  365. return;
  366. List <UnknownAttributeDescriptor> attrs = parser.UnknownMainAttributes;
  367. if (attrs == null || attrs.Count == 0)
  368. return;
  369. foreach (UnknownAttributeDescriptor uad in attrs)
  370. SetCustomAttribute (method, uad);
  371. }
  372. #endif
  373. protected virtual void AddStatementsToInitMethod (CodeMemberMethod method)
  374. {
  375. }
  376. void AddLiteralSubObject (ControlBuilder builder, string str)
  377. {
  378. if (!builder.HasAspCode) {
  379. CodeObjectCreateExpression expr;
  380. expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
  381. AddParsedSubObjectStmt (builder, expr);
  382. } else {
  383. CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
  384. methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
  385. methodRef.MethodName = "Write";
  386. CodeMethodInvokeExpression expr;
  387. expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
  388. builder.renderMethod.Statements.Add (AddLinePragma (expr, builder));
  389. }
  390. }
  391. string TrimDB (string value, bool trimTail)
  392. {
  393. string str = value.Trim ();
  394. int len = str.Length;
  395. int idx = str.IndexOf ('#', 2) + 1;
  396. if (idx >= len)
  397. return String.Empty;
  398. if (trimTail)
  399. len -= 2;
  400. return str.Substring (idx, len - idx).Trim ();
  401. }
  402. CodeMethodInvokeExpression CreateEvalInvokeExpression (Regex regex, string value, int first, int second)
  403. {
  404. Match match = regex.Match (value);
  405. if (!match.Success)
  406. return null;
  407. Group secondGroup = match.Groups [second];
  408. CodeMethodInvokeExpression ret = new CodeMethodInvokeExpression ();
  409. ret.Method = new CodeMethodReferenceExpression (thisRef, "Eval");
  410. ret.Parameters.Add (new CodePrimitiveExpression (match.Groups [first].Value));
  411. if (secondGroup.Success)
  412. ret.Parameters.Add (new CodePrimitiveExpression (secondGroup.Value));
  413. return ret;
  414. }
  415. string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
  416. {
  417. value = TrimDB (value, true);
  418. CodeMemberMethod method;
  419. string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
  420. CodeExpression valueExpression = null;
  421. value = value.Trim ();
  422. #if NET_2_0
  423. bool need_if = false;
  424. if (StrUtils.StartsWith (value, "Bind", true)) {
  425. valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, 1, 4);
  426. if (valueExpression != null)
  427. need_if = true;
  428. } else
  429. #endif
  430. if (StrUtils.StartsWith (value, "Eval", true))
  431. valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, 1, 4);
  432. if (valueExpression == null)
  433. valueExpression = new CodeSnippetExpression (value);
  434. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
  435. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  436. // This should be a CodePropertyReferenceExpression for properties... but it works anyway
  437. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
  438. CodeExpression expr;
  439. if (type == typeof (string)) {
  440. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  441. CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
  442. tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
  443. tostring.Parameters.Add (valueExpression);
  444. expr = tostring;
  445. } else
  446. expr = new CodeCastExpression (type, valueExpression);
  447. CodeAssignStatement assign = new CodeAssignStatement (field, expr);
  448. #if NET_2_0
  449. if (need_if) {
  450. CodeExpression page = new CodePropertyReferenceExpression (thisRef, "Page");
  451. CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
  452. CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
  453. CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
  454. method.Statements.Add (ccs);
  455. }
  456. else
  457. #endif
  458. method.Statements.Add (assign);
  459. mainClass.Members.Add (method);
  460. return method.Name;
  461. }
  462. void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
  463. {
  464. CodeMemberMethod method = builder.method;
  465. bool isWritable = IsWritablePropertyOrField (member);
  466. if (isDataBound && isWritable) {
  467. string dbMethodName = DataBoundProperty (builder, type, var_name, att);
  468. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  469. return;
  470. }
  471. #if NET_2_0
  472. else if (isExpression && isWritable) {
  473. AddExpressionAssign (method, builder, member, type, var_name, att);
  474. return;
  475. }
  476. #endif
  477. CodeAssignStatement assign = new CodeAssignStatement ();
  478. assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
  479. currentLocation = builder.location;
  480. assign.Right = GetExpressionFromString (type, att, member);
  481. method.Statements.Add (AddLinePragma (assign, builder));
  482. }
  483. bool IsDirective (string value, char directiveChar)
  484. {
  485. if (value == null || value == String.Empty)
  486. return false;
  487. value = value.Trim ();
  488. if (!StrUtils.StartsWith (value, "<%") || !StrUtils.EndsWith (value, "%>"))
  489. return false;
  490. int dcIndex = value.IndexOf (directiveChar, 2);
  491. if (dcIndex == -1)
  492. return false;
  493. if (dcIndex == 2)
  494. return true;
  495. dcIndex--;
  496. while (dcIndex >= 2) {
  497. if (!Char.IsWhiteSpace (value [dcIndex]))
  498. return false;
  499. dcIndex--;
  500. }
  501. return true;
  502. }
  503. bool IsDataBound (string value)
  504. {
  505. return IsDirective (value, '#');
  506. }
  507. #if NET_2_0
  508. bool IsExpression (string value)
  509. {
  510. return IsDirective (value, '$');
  511. }
  512. void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
  513. {
  514. string str = TrimDB (value, false);
  515. if (StrUtils.StartsWith (str, "Bind", true)) {
  516. Match match = bindRegex.Match (str);
  517. if (match.Success) {
  518. string bindingName = match.Groups [1].Value;
  519. TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
  520. if (templateBuilder == null || templateBuilder.BindingDirection == BindingDirection.OneWay)
  521. throw new HttpException ("Bind expression not allowed in this context.");
  522. string id = builder.attribs ["ID"] as string;
  523. if (id == null)
  524. throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
  525. templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
  526. }
  527. }
  528. }
  529. #endif
  530. /*
  531. static bool InvariantCompare (string a, string b)
  532. {
  533. return (0 == String.Compare (a, b, false, CultureInfo.InvariantCulture));
  534. }
  535. */
  536. static bool InvariantCompareNoCase (string a, string b)
  537. {
  538. return (0 == String.Compare (a, b, true, CultureInfo.InvariantCulture));
  539. }
  540. static MemberInfo GetFieldOrProperty (Type type, string name)
  541. {
  542. MemberInfo member = null;
  543. try {
  544. member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
  545. } catch {}
  546. if (member != null)
  547. return member;
  548. try {
  549. member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
  550. } catch {}
  551. return member;
  552. }
  553. static bool IsWritablePropertyOrField (MemberInfo member)
  554. {
  555. PropertyInfo pi = member as PropertyInfo;
  556. if (pi != null)
  557. return pi.CanWrite;
  558. FieldInfo fi = member as FieldInfo;
  559. if (fi != null)
  560. return !fi.IsInitOnly;
  561. throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
  562. }
  563. bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
  564. string attValue, string prefix)
  565. {
  566. int hyphen = id.IndexOf ('-');
  567. bool isPropertyInfo = (member is PropertyInfo);
  568. bool isDataBound = IsDataBound (attValue);
  569. #if NET_2_0
  570. bool isExpression = !isDataBound && IsExpression (attValue);
  571. #else
  572. bool isExpression = false;
  573. #endif
  574. Type type;
  575. if (isPropertyInfo) {
  576. type = ((PropertyInfo) member).PropertyType;
  577. } else {
  578. type = ((FieldInfo) member).FieldType;
  579. }
  580. if (InvariantCompareNoCase (member.Name, id)) {
  581. #if NET_2_0
  582. if (isDataBound)
  583. RegisterBindingInfo (builder, member.Name, ref attValue);
  584. #endif
  585. if (!IsWritablePropertyOrField (member))
  586. return false;
  587. AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
  588. return true;
  589. }
  590. if (hyphen == -1)
  591. return false;
  592. string prop_field = id.Replace ("-", ".");
  593. string [] parts = prop_field.Split (new char [] {'.'});
  594. int length = parts.Length;
  595. if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
  596. return false;
  597. if (length > 2) {
  598. MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
  599. if (sub_member == null)
  600. return false;
  601. string new_prefix = prefix + member.Name + ".";
  602. string new_id = id.Substring (hyphen + 1);
  603. return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
  604. }
  605. MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
  606. if (!(subpf is PropertyInfo))
  607. return false;
  608. PropertyInfo subprop = (PropertyInfo) subpf;
  609. if (subprop.CanWrite == false)
  610. return false;
  611. bool is_bool = (subprop.PropertyType == typeof (bool));
  612. if (!is_bool && attValue == null)
  613. return false; // Font-Size -> Font-Size="" as html
  614. string val = attValue;
  615. if (attValue == null && is_bool)
  616. val = "true"; // Font-Bold <=> Font-Bold="true"
  617. #if NET_2_0
  618. if (isDataBound)
  619. RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
  620. #endif
  621. AddCodeForPropertyOrField (builder, subprop.PropertyType,
  622. prefix + member.Name + "." + subprop.Name,
  623. val, subprop, isDataBound, isExpression);
  624. return true;
  625. }
  626. #if NET_2_0
  627. CodeExpression CompileExpression (MemberInfo member, Type type, string value, bool useSetAttribute)
  628. {
  629. // First let's find the correct expression builder
  630. value = value.Substring (3, value.Length - 5).Trim ();
  631. int colon = value.IndexOf (':');
  632. if (colon == -1)
  633. return null;
  634. string prefix = value.Substring (0, colon).Trim ();
  635. string expr = value.Substring (colon + 1).Trim ();
  636. System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration ("");
  637. if (config == null)
  638. return null;
  639. CompilationSection cs = (CompilationSection)config.GetSection ("system.web/compilation");
  640. if (cs == null)
  641. return null;
  642. if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
  643. return null;
  644. System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
  645. if (ceb == null)
  646. return null;
  647. string builderType = ceb.Type;
  648. Type t;
  649. try {
  650. t = HttpApplication.LoadType (builderType, true);
  651. } catch (Exception e) {
  652. throw new HttpException (String.Format ("Failed to load expression builder type `{0}'", builderType), e);
  653. }
  654. if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
  655. throw new HttpException (String.Format ("Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder", builderType));
  656. System.Web.Compilation.ExpressionBuilder eb = null;
  657. object parsedData;
  658. ExpressionBuilderContext ctx;
  659. try {
  660. eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
  661. ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
  662. parsedData = eb.ParseExpression (expr, type, ctx);
  663. } catch (Exception e) {
  664. throw new HttpException (String.Format ("Failed to create an instance of type `{0}'", builderType), e);
  665. }
  666. BoundPropertyEntry bpe = CreateBoundPropertyEntry (member as PropertyInfo, prefix, expr, useSetAttribute);
  667. return eb.GetCodeExpression (bpe, parsedData, ctx);
  668. }
  669. void AddExpressionAssign (CodeMemberMethod method, ControlBuilder builder, MemberInfo member, Type type, string name, string value)
  670. {
  671. CodeExpression expr = CompileExpression (member, type, value, false);
  672. if (expr == null)
  673. return;
  674. CodeAssignStatement assign = new CodeAssignStatement ();
  675. assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
  676. assign.Right = expr;
  677. builder.method.Statements.Add (AddLinePragma (assign, builder));
  678. }
  679. BoundPropertyEntry CreateBoundPropertyEntry (PropertyInfo pi, string prefix, string expr, bool useSetAttribute)
  680. {
  681. BoundPropertyEntry ret = new BoundPropertyEntry ();
  682. ret.Expression = expr;
  683. ret.ExpressionPrefix = prefix;
  684. ret.Generated = false;
  685. if (pi != null) {
  686. ret.Name = pi.Name;
  687. ret.PropertyInfo = pi;
  688. ret.Type = pi.PropertyType;
  689. }
  690. ret.UseSetAttribute = useSetAttribute;
  691. return ret;
  692. }
  693. void AssignPropertyFromResources (ControlBuilder builder, MemberInfo mi, string attvalue)
  694. {
  695. bool isProperty = mi.MemberType == MemberTypes.Property;
  696. bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
  697. if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
  698. return;
  699. string memberName = mi.Name;
  700. string resname = String.Concat (attvalue, ".", memberName);
  701. // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
  702. string inputFile = parser.InputFile;
  703. string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
  704. if (StrUtils.StartsWith (inputFile, physPath))
  705. inputFile = parser.InputFile.Substring (physPath.Length - 1);
  706. else
  707. return;
  708. char dsc = System.IO.Path.DirectorySeparatorChar;
  709. if (dsc != '/')
  710. inputFile = inputFile.Replace (dsc, '/');
  711. object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
  712. if (obj == null)
  713. return;
  714. if (!isProperty && !isField)
  715. return; // an "impossible" case
  716. CodeAssignStatement assign = new CodeAssignStatement ();
  717. assign.Left = new CodePropertyReferenceExpression (ctrlVar, memberName);
  718. assign.Right = ResourceExpressionBuilder.CreateGetLocalResourceObject (mi, resname);
  719. builder.method.Statements.Add (AddLinePragma (assign, builder));
  720. }
  721. void AssignPropertiesFromResources (ControlBuilder builder, Type controlType, string attvalue)
  722. {
  723. // Process all public fields and properties of the control. We don't use GetMembers to make the code
  724. // faster
  725. FieldInfo [] fields = controlType.GetFields (
  726. BindingFlags.Instance | BindingFlags.Static |
  727. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  728. PropertyInfo [] properties = controlType.GetProperties (
  729. BindingFlags.Instance | BindingFlags.Static |
  730. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  731. foreach (FieldInfo fi in fields)
  732. AssignPropertyFromResources (builder, fi, attvalue);
  733. foreach (PropertyInfo pi in properties)
  734. AssignPropertyFromResources (builder, pi, attvalue);
  735. }
  736. void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
  737. {
  738. if (attvalue == null || attvalue.Length == 0)
  739. return;
  740. Type controlType = builder.ControlType;
  741. if (controlType == null)
  742. return;
  743. AssignPropertiesFromResources (builder, controlType, attvalue);
  744. }
  745. #endif
  746. void AddEventAssign (CodeMemberMethod method, ControlBuilder builder, string name, Type type, string value)
  747. {
  748. //"__ctrl.{0} += new {1} (this.{2});"
  749. CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
  750. CodeDelegateCreateExpression create;
  751. create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
  752. CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
  753. method.Statements.Add (attach);
  754. }
  755. void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
  756. {
  757. EventInfo [] ev_info = null;
  758. Type type = builder.ControlType;
  759. string attvalue = builder.attribs [id] as string;
  760. if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
  761. if (ev_info == null)
  762. ev_info = type.GetEvents ();
  763. string id_as_event = id.Substring (2);
  764. foreach (EventInfo ev in ev_info){
  765. if (InvariantCompareNoCase (ev.Name, id_as_event)){
  766. AddEventAssign (builder.method,
  767. builder,
  768. ev.Name,
  769. ev.EventHandlerType,
  770. attvalue);
  771. return;
  772. }
  773. }
  774. }
  775. #if NET_2_0
  776. if (id.ToLower () == "meta:resourcekey") {
  777. AssignPropertiesFromResources (builder, attvalue);
  778. return;
  779. }
  780. #endif
  781. int hyphen = id.IndexOf ('-');
  782. string alt_id = id;
  783. if (hyphen != -1)
  784. alt_id = id.Substring (0, hyphen);
  785. MemberInfo fop = GetFieldOrProperty (type, alt_id);
  786. if (fop != null) {
  787. if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
  788. return;
  789. }
  790. if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
  791. throw new ParseException (builder.location, "Unrecognized attribute: " + id);
  792. CodeMemberMethod method = builder.method;
  793. bool isDatabound = IsDataBound (attvalue);
  794. #if NET_2_0
  795. bool isExpression = !isDatabound && IsExpression (attvalue);
  796. #endif
  797. if (isDatabound) {
  798. string value = attvalue.Substring (3, attvalue.Length - 5).Trim ();
  799. CodeExpression valueExpression = null;
  800. #if NET_2_0
  801. if (StrUtils.StartsWith (value, "Bind", true))
  802. valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, 1, 4);
  803. else
  804. #endif
  805. if (StrUtils.StartsWith (value, "Eval", true))
  806. valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, 1, 4);
  807. if (valueExpression == null && value != null && value.Trim () != String.Empty)
  808. valueExpression = new CodeSnippetExpression (value);
  809. CreateDBAttributeMethod (builder, id, valueExpression);
  810. } else {
  811. CodeCastExpression cast;
  812. CodeMethodReferenceExpression methodExpr;
  813. CodeMethodInvokeExpression expr;
  814. cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
  815. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  816. expr = new CodeMethodInvokeExpression (methodExpr);
  817. expr.Parameters.Add (new CodePrimitiveExpression (id));
  818. CodeExpression valueExpr = null;
  819. #if NET_2_0
  820. if (isExpression)
  821. valueExpr = CompileExpression (null, typeof (string), attvalue, true);
  822. if (valueExpr == null)
  823. #endif
  824. valueExpr = new CodePrimitiveExpression (attvalue);
  825. expr.Parameters.Add (valueExpr);
  826. method.Statements.Add (AddLinePragma (expr, builder));
  827. }
  828. }
  829. protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
  830. {
  831. this.dataBoundAtts = 0;
  832. IDictionary atts = builder.attribs;
  833. if (atts == null || atts.Count == 0)
  834. return;
  835. foreach (string id in atts.Keys) {
  836. if (InvariantCompareNoCase (id, "runat"))
  837. continue;
  838. // ID is assigned in BuildControltree
  839. if (InvariantCompareNoCase (id, "id"))
  840. continue;
  841. #if NET_2_0
  842. /* we skip SkinID here as it's assigned in BuildControlTree */
  843. if (InvariantCompareNoCase (id, "skinid"))
  844. continue;
  845. if (InvariantCompareNoCase (id, "meta:resourcekey"))
  846. continue; // ignore, this one's processed at the very end of
  847. // the method
  848. #endif
  849. CreateAssignStatementFromAttribute (builder, id);
  850. }
  851. }
  852. void CreateDBAttributeMethod (ControlBuilder builder, string attr, CodeExpression code)
  853. {
  854. if (code == null)
  855. return;
  856. string id = builder.GetNextID (null);
  857. string dbMethodName = "__DataBind_" + id;
  858. CodeMemberMethod method = builder.method;
  859. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  860. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
  861. CodeCastExpression cast;
  862. CodeMethodReferenceExpression methodExpr;
  863. CodeMethodInvokeExpression expr;
  864. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  865. cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
  866. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  867. expr = new CodeMethodInvokeExpression (methodExpr);
  868. expr.Parameters.Add (new CodePrimitiveExpression (attr));
  869. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  870. tostring.Method = new CodeMethodReferenceExpression (
  871. new CodeTypeReferenceExpression (typeof (Convert)),
  872. "ToString");
  873. tostring.Parameters.Add (code);
  874. expr.Parameters.Add (tostring);
  875. method.Statements.Add (expr);
  876. mainClass.Members.Add (method);
  877. }
  878. void AddRenderControl (ControlBuilder builder)
  879. {
  880. CodeIndexerExpression indexer = new CodeIndexerExpression ();
  881. indexer.TargetObject = new CodePropertyReferenceExpression (
  882. new CodeArgumentReferenceExpression ("parameterContainer"),
  883. "Controls");
  884. indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
  885. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
  886. invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
  887. builder.renderMethod.Statements.Add (invoke);
  888. builder.renderIndex++;
  889. }
  890. protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
  891. {
  892. if (parent == null || child == null)
  893. return;
  894. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
  895. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
  896. object [] atts = null;
  897. if (child.ControlType != null)
  898. atts = child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
  899. if (atts != null && atts.Length > 0) {
  900. PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
  901. CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
  902. CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
  903. build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
  904. build.Parameters.Add (new CodePrimitiveExpression (child.ID));
  905. #if NET_1_1
  906. if (pca.Shared)
  907. build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
  908. else
  909. #endif
  910. build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
  911. build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
  912. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
  913. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
  914. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
  915. build.Parameters.Add (new CodeDelegateCreateExpression (
  916. new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
  917. thisRef, child.method.Name));
  918. parent.methodStatements.Add (AddLinePragma (build, parent));
  919. if (parent.HasAspCode)
  920. AddRenderControl (parent);
  921. return;
  922. }
  923. if (child.isProperty || parent.ChildrenAsProperties) {
  924. expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
  925. parent.methodStatements.Add (AddLinePragma (expr, parent));
  926. return;
  927. }
  928. parent.methodStatements.Add (AddLinePragma (expr, parent));
  929. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
  930. if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType))
  931. AddParsedSubObjectStmt (parent, field);
  932. else {
  933. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
  934. invoke.Parameters.Add (field);
  935. parent.methodStatements.Add (AddLinePragma (invoke, parent));
  936. }
  937. if (parent.HasAspCode)
  938. AddRenderControl (parent);
  939. }
  940. void AddTemplateInvocation (ControlBuilder builder, string name, string methodName)
  941. {
  942. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  943. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  944. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  945. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  946. newCompiled.Parameters.Add (newBuild);
  947. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  948. builder.method.Statements.Add (AddLinePragma (assign, builder));
  949. }
  950. #if NET_2_0
  951. void AddBindableTemplateInvocation (ControlBuilder builder, string name, string methodName, string extractMethodName)
  952. {
  953. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  954. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  955. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  956. CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
  957. new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);
  958. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
  959. newCompiled.Parameters.Add (newBuild);
  960. newCompiled.Parameters.Add (newExtract);
  961. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  962. builder.method.Statements.Add (AddLinePragma (assign, builder));
  963. }
  964. string CreateExtractValuesMethod (TemplateBuilder builder)
  965. {
  966. CodeMemberMethod method = new CodeMemberMethod ();
  967. method.Name = "__ExtractValues_" + builder.ID;
  968. method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  969. method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
  970. CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
  971. arg.Type = new CodeTypeReference (typeof (Control));
  972. arg.Name = "__container";
  973. method.Parameters.Add (arg);
  974. mainClass.Members.Add (method);
  975. CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
  976. newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
  977. method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
  978. CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
  979. if (builder.Bindings != null) {
  980. Hashtable hash = new Hashtable ();
  981. foreach (TemplateBinding binding in builder.Bindings) {
  982. CodeConditionStatement sif;
  983. CodeVariableReferenceExpression control;
  984. CodeAssignStatement assign;
  985. if (hash [binding.ControlId] == null) {
  986. CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
  987. method.Statements.Add (dec);
  988. CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
  989. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
  990. invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
  991. assign = new CodeAssignStatement ();
  992. control = new CodeVariableReferenceExpression (binding.ControlId);
  993. assign.Left = control;
  994. assign.Right = new CodeCastExpression (binding.ControlType, invoke);
  995. method.Statements.Add (assign);
  996. sif = new CodeConditionStatement ();
  997. sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
  998. method.Statements.Add (sif);
  999. hash [binding.ControlId] = sif;
  1000. }
  1001. sif = (CodeConditionStatement) hash [binding.ControlId];
  1002. control = new CodeVariableReferenceExpression (binding.ControlId);
  1003. assign = new CodeAssignStatement ();
  1004. assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
  1005. assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
  1006. sif.TrueStatements.Add (assign);
  1007. }
  1008. }
  1009. method.Statements.Add (new CodeMethodReturnStatement (tableExp));
  1010. return method.Name;
  1011. }
  1012. void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
  1013. {
  1014. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  1015. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  1016. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  1017. newCompiled.Parameters.Add (newBuild);
  1018. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
  1019. invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
  1020. invoke.Parameters.Add (newCompiled);
  1021. method.Statements.Add (AddLinePragma (invoke, cbuilder));
  1022. }
  1023. #endif
  1024. void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
  1025. {
  1026. if (cr.Code == null || cr.Code.Trim () == "")
  1027. return;
  1028. if (!cr.IsAssign) {
  1029. CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
  1030. parent.renderMethod.Statements.Add (AddLinePragma (code, cr));
  1031. return;
  1032. }
  1033. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
  1034. expr.Method = new CodeMethodReferenceExpression (
  1035. new CodeArgumentReferenceExpression ("__output"),
  1036. "Write");
  1037. expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
  1038. parent.renderMethod.Statements.Add (AddLinePragma (expr, cr));
  1039. }
  1040. static PropertyInfo GetContainerProperty (Type type, string[] propNames)
  1041. {
  1042. PropertyInfo prop;
  1043. foreach (string name in propNames) {
  1044. prop = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
  1045. if (prop != null)
  1046. return prop;
  1047. }
  1048. return null;
  1049. }
  1050. #if !NET_2_0
  1051. static string[] containerPropNames = {"Items", "Rows"};
  1052. #endif
  1053. static Type GetContainerType (ControlBuilder builder)
  1054. {
  1055. Type type = builder.BindingContainerType;
  1056. #if NET_2_0
  1057. return type;
  1058. #else
  1059. PropertyInfo prop = GetContainerProperty (type, containerPropNames);
  1060. if (prop == null)
  1061. return type;
  1062. Type ptype = prop.PropertyType;
  1063. if (!typeof (ICollection).IsAssignableFrom (ptype))
  1064. return type;
  1065. prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
  1066. if (prop == null)
  1067. return type;
  1068. return prop.PropertyType;
  1069. #endif
  1070. }
  1071. CodeMemberMethod CreateDBMethod (ControlBuilder builder, string name, Type container, Type target)
  1072. {
  1073. CodeMemberMethod method = new CodeMemberMethod ();
  1074. method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  1075. method.Name = name;
  1076. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
  1077. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
  1078. CodeTypeReference containerRef = new CodeTypeReference (container);
  1079. CodeTypeReference targetRef = new CodeTypeReference (target);
  1080. CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
  1081. decl.Name = "Container";
  1082. decl.Type = containerRef;
  1083. method.Statements.Add (decl);
  1084. decl = new CodeVariableDeclarationStatement();
  1085. decl.Name = "target";
  1086. decl.Type = targetRef;
  1087. method.Statements.Add (decl);
  1088. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  1089. CodeAssignStatement assign = new CodeAssignStatement ();
  1090. assign.Left = targetExpr;
  1091. assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
  1092. method.Statements.Add (AddLinePragma (assign, builder));
  1093. assign = new CodeAssignStatement ();
  1094. assign.Left = new CodeVariableReferenceExpression ("Container");
  1095. assign.Right = new CodeCastExpression (containerRef,
  1096. new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
  1097. method.Statements.Add (AddLinePragma (assign, builder));
  1098. return method;
  1099. }
  1100. void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
  1101. {
  1102. if (db.Code == null || db.Code.Trim () == "")
  1103. return;
  1104. EnsureID (db);
  1105. CreateField (db, false);
  1106. string dbMethodName = "__DataBind_" + db.ID;
  1107. // Add the method that builds the DataBoundLiteralControl
  1108. InitMethod (db, false, false);
  1109. CodeMemberMethod method = db.method;
  1110. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  1111. method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  1112. // Add the DataBind handler
  1113. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
  1114. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  1115. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  1116. invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
  1117. invoke.Parameters.Add (new CodePrimitiveExpression (0));
  1118. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  1119. tostring.Method = new CodeMethodReferenceExpression (
  1120. new CodeTypeReferenceExpression (typeof (Convert)),
  1121. "ToString");
  1122. tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
  1123. invoke.Parameters.Add (tostring);
  1124. method.Statements.Add (AddLinePragma (invoke, builder));
  1125. mainClass.Members.Add (method);
  1126. AddChildCall (builder, db);
  1127. }
  1128. void FlushText (ControlBuilder builder, StringBuilder sb)
  1129. {
  1130. if (sb.Length > 0) {
  1131. AddLiteralSubObject (builder, sb.ToString ());
  1132. sb.Length = 0;
  1133. }
  1134. }
  1135. protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
  1136. {
  1137. EnsureID (builder);
  1138. bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
  1139. if (!isTemplate && !inTemplate) {
  1140. CreateField (builder, true);
  1141. } else if (!isTemplate) {
  1142. bool doCheck = false;
  1143. #if NET_2_0
  1144. bool singleInstance = false;
  1145. ControlBuilder pb = builder.parentBuilder;
  1146. TemplateBuilder tpb;
  1147. while (pb != null) {
  1148. tpb = pb as TemplateBuilder;
  1149. if (tpb == null) {
  1150. pb = pb.parentBuilder;
  1151. continue;
  1152. }
  1153. if (tpb.TemplateInstance == TemplateInstance.Single)
  1154. singleInstance = true;
  1155. break;
  1156. }
  1157. if (!singleInstance)
  1158. #endif
  1159. builder.ID = builder.GetNextID (null);
  1160. #if NET_2_0
  1161. else
  1162. doCheck = true;
  1163. #endif
  1164. CreateField (builder, doCheck);
  1165. }
  1166. InitMethod (builder, isTemplate, childrenAsProperties);
  1167. if (!isTemplate || builder.GetType () == typeof (RootBuilder))
  1168. CreateAssignStatementsFromAttributes (builder);
  1169. if (builder.Children != null && builder.Children.Count > 0) {
  1170. StringBuilder sb = new StringBuilder ();
  1171. foreach (object b in builder.Children) {
  1172. if (b is string) {
  1173. sb.Append ((string) b);
  1174. continue;
  1175. }
  1176. FlushText (builder, sb);
  1177. if (b is ObjectTagBuilder) {
  1178. ProcessObjectTag ((ObjectTagBuilder) b);
  1179. continue;
  1180. }
  1181. StringPropertyBuilder pb = b as StringPropertyBuilder;
  1182. if (pb != null){
  1183. if (pb.Children != null && pb.Children.Count > 0) {
  1184. StringBuilder asb = new StringBuilder ();
  1185. foreach (string s in pb.Children)
  1186. asb.Append (s);
  1187. CodeMemberMethod method = builder.method;
  1188. CodeAssignStatement assign = new CodeAssignStatement ();
  1189. assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
  1190. assign.Right = new CodePrimitiveExpression (asb.ToString ());
  1191. method.Statements.Add (AddLinePragma (assign, builder));
  1192. }
  1193. continue;
  1194. }
  1195. #if NET_2_0
  1196. if (b is ContentBuilderInternal) {
  1197. ContentBuilderInternal cb = (ContentBuilderInternal) b;
  1198. CreateControlTree (cb, false, true);
  1199. AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
  1200. continue;
  1201. }
  1202. #endif
  1203. // Ignore TemplateBuilders - they are processed in InitMethod
  1204. if (b is TemplateBuilder)
  1205. continue;
  1206. if (b is CodeRenderBuilder) {
  1207. AddCodeRender (builder, (CodeRenderBuilder) b);
  1208. continue;
  1209. }
  1210. if (b is DataBindingBuilder) {
  1211. AddDataBindingLiteral (builder, (DataBindingBuilder) b);
  1212. continue;
  1213. }
  1214. if (b is ControlBuilder) {
  1215. ControlBuilder child = (ControlBuilder) b;
  1216. CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
  1217. AddChildCall (builder, child);
  1218. continue;
  1219. }
  1220. throw new Exception ("???");
  1221. }
  1222. FlushText (builder, sb);
  1223. }
  1224. if (builder.defaultPropertyBuilder != null) {
  1225. ControlBuilder b = builder.defaultPropertyBuilder;
  1226. CreateControlTree (b, false, true);
  1227. AddChildCall (builder, b);
  1228. }
  1229. if (builder.HasAspCode) {
  1230. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1231. m.TargetObject = thisRef;
  1232. m.MethodName = builder.renderMethod.Name;
  1233. CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
  1234. create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
  1235. create.TargetObject = thisRef;
  1236. create.MethodName = builder.renderMethod.Name;
  1237. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  1238. invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
  1239. invoke.Parameters.Add (create);
  1240. builder.methodStatements.Add (invoke);
  1241. }
  1242. #if NET_2_0
  1243. if (builder is RootBuilder)
  1244. if (!String.IsNullOrEmpty (parser.MetaResourceKey))
  1245. AssignPropertiesFromResources (builder, parser.BaseType, parser.MetaResourceKey);
  1246. if ((!isTemplate || builder is RootBuilder) && builder.attribs != null && builder.attribs ["meta:resourcekey"] != null)
  1247. CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
  1248. #endif
  1249. if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
  1250. builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  1251. }
  1252. protected internal override void CreateMethods ()
  1253. {
  1254. base.CreateMethods ();
  1255. CreateProperties ();
  1256. CreateControlTree (parser.RootBuilder, false, false);
  1257. CreateFrameworkInitializeMethod ();
  1258. }
  1259. #if NET_2_0
  1260. void CallBaseFrameworkInitialize (CodeMemberMethod method)
  1261. {
  1262. CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
  1263. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
  1264. method.Statements.Add (invoke);
  1265. }
  1266. #endif
  1267. void CallSetStringResourcePointer (CodeMemberMethod method)
  1268. {
  1269. CodeFieldReferenceExpression stringResource = GetMainClassFieldReferenceExpression ("__stringResource");
  1270. method.Statements.Add (
  1271. new CodeMethodInvokeExpression (
  1272. thisRef,
  1273. "SetStringResourcePointer",
  1274. new CodeExpression[] {stringResource, new CodePrimitiveExpression (0)})
  1275. );
  1276. }
  1277. void CreateFrameworkInitializeMethod ()
  1278. {
  1279. CodeMemberMethod method = new CodeMemberMethod ();
  1280. method.Name = "FrameworkInitialize";
  1281. method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1282. PrependStatementsToFrameworkInitialize (method);
  1283. #if NET_2_0
  1284. CallBaseFrameworkInitialize (method);
  1285. #endif
  1286. CallSetStringResourcePointer (method);
  1287. AppendStatementsToFrameworkInitialize (method);
  1288. mainClass.Members.Add (method);
  1289. }
  1290. protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
  1291. {
  1292. }
  1293. protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
  1294. {
  1295. if (!parser.EnableViewState) {
  1296. CodeAssignStatement stmt = new CodeAssignStatement ();
  1297. stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
  1298. stmt.Right = new CodePrimitiveExpression (false);
  1299. method.Statements.Add (stmt);
  1300. }
  1301. CodeMethodReferenceExpression methodExpr;
  1302. methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
  1303. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
  1304. method.Statements.Add (new CodeExpressionStatement (expr));
  1305. }
  1306. protected override void AddApplicationAndSessionObjects ()
  1307. {
  1308. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
  1309. CreateFieldForObject (tag.Type, tag.ObjectID);
  1310. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
  1311. }
  1312. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
  1313. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
  1314. }
  1315. }
  1316. protected override void CreateStaticFields ()
  1317. {
  1318. base.CreateStaticFields ();
  1319. CodeMemberField fld = new CodeMemberField (typeof (object), "__stringResource");
  1320. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  1321. fld.InitExpression = new CodePrimitiveExpression (null);
  1322. mainClass.Members.Add (fld);
  1323. }
  1324. protected void ProcessObjectTag (ObjectTagBuilder tag)
  1325. {
  1326. string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
  1327. CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
  1328. }
  1329. void CreateProperties ()
  1330. {
  1331. if (!parser.AutoEventWireup) {
  1332. CreateAutoEventWireup ();
  1333. } else {
  1334. CreateAutoHandlers ();
  1335. }
  1336. CreateApplicationInstance ();
  1337. }
  1338. void CreateApplicationInstance ()
  1339. {
  1340. CodeMemberProperty prop = new CodeMemberProperty ();
  1341. Type appType = typeof (HttpApplication);
  1342. prop.Type = new CodeTypeReference (appType);
  1343. prop.Name = "ApplicationInstance";
  1344. prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
  1345. CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
  1346. propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
  1347. CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
  1348. prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
  1349. #if NET_2_0
  1350. if (partialClass != null)
  1351. partialClass.Members.Add (prop);
  1352. else
  1353. #endif
  1354. mainClass.Members.Add (prop);
  1355. }
  1356. void CreateAutoHandlers ()
  1357. {
  1358. // Create AutoHandlers property
  1359. CodeMemberProperty prop = new CodeMemberProperty ();
  1360. prop.Type = new CodeTypeReference (typeof (int));
  1361. prop.Name = "AutoHandlers";
  1362. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1363. CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
  1364. CodeFieldReferenceExpression fldRef ;
  1365. fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
  1366. ret.Expression = fldRef;
  1367. prop.GetStatements.Add (ret);
  1368. prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
  1369. #if NET_2_0
  1370. CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
  1371. prop.CustomAttributes.Add (attr);
  1372. #endif
  1373. mainClass.Members.Add (prop);
  1374. // Add the __autoHandlers field
  1375. CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
  1376. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  1377. mainClass.Members.Add (fld);
  1378. }
  1379. void CreateAutoEventWireup ()
  1380. {
  1381. // The getter returns false
  1382. CodeMemberProperty prop = new CodeMemberProperty ();
  1383. prop.Type = new CodeTypeReference (typeof (bool));
  1384. prop.Name = "SupportAutoEvents";
  1385. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1386. prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
  1387. mainClass.Members.Add (prop);
  1388. }
  1389. #if NET_2_0
  1390. protected virtual string HandleUrlProperty (string str, MemberInfo member)
  1391. {
  1392. return str;
  1393. }
  1394. #endif
  1395. TypeConverter GetConverterForMember (MemberInfo member)
  1396. {
  1397. TypeConverterAttribute tca = null;
  1398. object[] attrs;
  1399. #if NET_2_0
  1400. attrs = member.GetCustomAttributes (typeof (TypeConverterAttribute), true);
  1401. if (attrs.Length > 0)
  1402. tca = attrs [0] as TypeConverterAttribute;
  1403. #else
  1404. attrs = member.GetCustomAttributes (true);
  1405. foreach (object attr in attrs) {
  1406. tca = attr as TypeConverterAttribute;
  1407. if (tca != null)
  1408. break;
  1409. }
  1410. #endif
  1411. if (tca == null)
  1412. return null;
  1413. string typeName = tca.ConverterTypeName;
  1414. if (typeName == null || typeName.Length == 0)
  1415. return null;
  1416. Type t = null;
  1417. try {
  1418. t = HttpApplication.LoadType (typeName);
  1419. } catch (Exception) {
  1420. // ignore
  1421. }
  1422. if (t == null)
  1423. return null;
  1424. return (TypeConverter) Activator.CreateInstance (t);
  1425. }
  1426. CodeExpression CreateNullableExpression (Type type, CodeExpression inst, bool nullable)
  1427. {
  1428. #if NET_2_0
  1429. if (!nullable)
  1430. return inst;
  1431. return new CodeObjectCreateExpression (
  1432. type,
  1433. new CodeExpression[] {inst}
  1434. );
  1435. #else
  1436. return inst;
  1437. #endif
  1438. }
  1439. bool SafeCanConvertFrom (Type type, TypeConverter cvt)
  1440. {
  1441. try {
  1442. return cvt.CanConvertFrom (type);
  1443. } catch (NotImplementedException) {
  1444. return false;
  1445. }
  1446. }
  1447. bool SafeCanConvertTo (Type type, TypeConverter cvt)
  1448. {
  1449. try {
  1450. return cvt.CanConvertTo (type);
  1451. } catch (NotImplementedException) {
  1452. return false;
  1453. }
  1454. }
  1455. CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
  1456. {
  1457. TypeConverter cvt = GetConverterForMember (member);
  1458. if (cvt != null && !SafeCanConvertFrom (typeof (string), cvt))
  1459. cvt = null;
  1460. object convertedFromAttr = null;
  1461. bool preConverted = false;
  1462. if (cvt != null && str != null) {
  1463. convertedFromAttr = cvt.ConvertFromInvariantString (str);
  1464. if (convertedFromAttr != null) {
  1465. type = convertedFromAttr.GetType ();
  1466. preConverted = true;
  1467. }
  1468. }
  1469. bool wasNullable = false;
  1470. Type originalType = type;
  1471. #if NET_2_0
  1472. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
  1473. Type[] types = type.GetGenericArguments();
  1474. originalType = type;
  1475. type = types[0]; // we're interested only in the first type here
  1476. wasNullable = true;
  1477. }
  1478. #endif
  1479. if (type == typeof (string)) {
  1480. if (preConverted)
  1481. return CreateNullableExpression (originalType,
  1482. new CodePrimitiveExpression ((string) convertedFromAttr),
  1483. wasNullable);
  1484. #if NET_2_0
  1485. object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
  1486. if (urlAttr.Length != 0)
  1487. str = HandleUrlProperty (str, member);
  1488. #endif
  1489. return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
  1490. } else if (type == typeof (bool)) {
  1491. if (preConverted)
  1492. return CreateNullableExpression (originalType,
  1493. new CodePrimitiveExpression ((bool) convertedFromAttr),
  1494. wasNullable);
  1495. if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
  1496. return CreateNullableExpression (originalType, new CodePrimitiveExpression (true), wasNullable);
  1497. else if (InvariantCompareNoCase (str, "false"))
  1498. return CreateNullableExpression (originalType, new CodePrimitiveExpression (false), wasNullable);
  1499. #if NET_2_0
  1500. else if (wasNullable && InvariantCompareNoCase(str, "null"))
  1501. return new CodePrimitiveExpression (null);
  1502. #endif
  1503. else
  1504. throw new ParseException (currentLocation,
  1505. "Value '" + str + "' is not a valid boolean.");
  1506. } else if (type == monoTypeType)
  1507. type = typeof (System.Type);
  1508. if (str == null)
  1509. return new CodePrimitiveExpression (null);
  1510. if (type.IsPrimitive)
  1511. return CreateNullableExpression (originalType,
  1512. new CodePrimitiveExpression (
  1513. Convert.ChangeType (preConverted ? convertedFromAttr : str,
  1514. type, CultureInfo.InvariantCulture)),
  1515. wasNullable);
  1516. if (type == typeof (string [])) {
  1517. string [] subs;
  1518. if (preConverted)
  1519. subs = (string[])convertedFromAttr;
  1520. else
  1521. subs = str.Split (',');
  1522. CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
  1523. expr.CreateType = new CodeTypeReference (typeof (string));
  1524. foreach (string v in subs)
  1525. expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
  1526. return CreateNullableExpression (originalType, expr, wasNullable);
  1527. }
  1528. if (type == typeof (Color)) {
  1529. Color c;
  1530. if (!preConverted) {
  1531. if (colorConverter == null)
  1532. colorConverter = TypeDescriptor.GetConverter (typeof (Color));
  1533. if (str.Trim().Length == 0) {
  1534. CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
  1535. return CreateNullableExpression (originalType,
  1536. new CodeFieldReferenceExpression (ft, "Empty"),
  1537. wasNullable);
  1538. }
  1539. try {
  1540. if (str.IndexOf (',') == -1) {
  1541. c = (Color) colorConverter.ConvertFromString (str);
  1542. } else {
  1543. int [] argb = new int [4];
  1544. argb [0] = 255;
  1545. string [] parts = str.Split (',');
  1546. int length = parts.Length;
  1547. if (length < 3)
  1548. throw new Exception ();
  1549. int basei = (length == 4) ? 0 : 1;
  1550. for (int i = length - 1; i >= 0; i--) {
  1551. argb [basei + i] = (int) Byte.Parse (parts [i]);
  1552. }
  1553. c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
  1554. }
  1555. } catch (Exception e) {
  1556. // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
  1557. // TypeConverter for Color fails to ConvertFromString.
  1558. // Hence this hack...
  1559. if (InvariantCompareNoCase ("LightGrey", str)) {
  1560. c = Color.LightGray;
  1561. } else {
  1562. throw new ParseException (currentLocation,
  1563. "Color " + str + " is not a valid color.", e);
  1564. }
  1565. }
  1566. } else
  1567. c = (Color)convertedFromAttr;
  1568. if (c.IsKnownColor) {
  1569. CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
  1570. if (c.IsSystemColor)
  1571. type = typeof (SystemColors);
  1572. expr.TargetObject = new CodeTypeReferenceExpression (type);
  1573. expr.FieldName = c.Name;
  1574. return CreateNullableExpression (originalType, expr, wasNullable);
  1575. } else {
  1576. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1577. m.TargetObject = new CodeTypeReferenceExpression (type);
  1578. m.MethodName = "FromArgb";
  1579. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  1580. invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
  1581. invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
  1582. invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
  1583. invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
  1584. return CreateNullableExpression (originalType, invoke, wasNullable);
  1585. }
  1586. }
  1587. TypeConverter converter = preConverted ? cvt :
  1588. wasNullable ? TypeDescriptor.GetConverter (type) :
  1589. TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
  1590. if (preConverted || (converter != null && SafeCanConvertFrom (typeof (string), converter))) {
  1591. object value = preConverted ? convertedFromAttr : converter.ConvertFromInvariantString (str);
  1592. if (SafeCanConvertTo (typeof (InstanceDescriptor), converter)) {
  1593. InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
  1594. if (wasNullable)
  1595. return CreateNullableExpression (originalType, GenerateInstance (idesc, true),
  1596. wasNullable);
  1597. return new CodeCastExpression (type, GenerateInstance (idesc, true));
  1598. }
  1599. CodeExpression exp = GenerateObjectInstance (value, false);
  1600. if (exp != null)
  1601. return CreateNullableExpression (originalType, exp, wasNullable);
  1602. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1603. m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
  1604. m.MethodName = "GetConverter";
  1605. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  1606. CodeTypeReference tref = new CodeTypeReference (type);
  1607. invoke.Parameters.Add (new CodeTypeOfExpression (tref));
  1608. invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
  1609. invoke.Parameters.Add (new CodePrimitiveExpression (str));
  1610. if (wasNullable)
  1611. return CreateNullableExpression (originalType, invoke, wasNullable);
  1612. return new CodeCastExpression (type, invoke);
  1613. }
  1614. Console.WriteLine ("Unknown type: " + type + " value: " + str);
  1615. return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
  1616. }
  1617. CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
  1618. {
  1619. CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
  1620. int n = 0;
  1621. foreach (object ob in idesc.Arguments) {
  1622. CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
  1623. if (exp == null) return null;
  1624. parameters [n++] = exp;
  1625. }
  1626. switch (idesc.MemberInfo.MemberType) {
  1627. case MemberTypes.Constructor:
  1628. CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
  1629. return new CodeObjectCreateExpression (tob, parameters);
  1630. case MemberTypes.Method:
  1631. CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1632. return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
  1633. case MemberTypes.Field:
  1634. CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1635. return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
  1636. case MemberTypes.Property:
  1637. CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1638. return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
  1639. }
  1640. throw new ParseException (currentLocation, "Invalid instance type.");
  1641. }
  1642. CodeExpression GenerateObjectInstance (object value, bool throwOnError)
  1643. {
  1644. if (value == null)
  1645. return new CodePrimitiveExpression (null);
  1646. if (value is System.Type) {
  1647. CodeTypeReference tref = new CodeTypeReference (value.ToString ());
  1648. return new CodeTypeOfExpression (tref);
  1649. }
  1650. Type t = value.GetType ();
  1651. if (t.IsPrimitive || value is string)
  1652. return new CodePrimitiveExpression (value);
  1653. if (t.IsArray) {
  1654. Array ar = (Array) value;
  1655. CodeExpression[] items = new CodeExpression [ar.Length];
  1656. for (int n=0; n<ar.Length; n++) {
  1657. CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
  1658. if (exp == null) return null;
  1659. items [n] = exp;
  1660. }
  1661. return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
  1662. }
  1663. TypeConverter converter = TypeDescriptor.GetConverter (t);
  1664. if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
  1665. InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
  1666. return GenerateInstance (idesc, throwOnError);
  1667. }
  1668. InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
  1669. if (desc != null) return GenerateInstance (desc, throwOnError);
  1670. if (throwOnError)
  1671. throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
  1672. else
  1673. return null;
  1674. }
  1675. InstanceDescriptor GetDefaultInstanceDescriptor (object value)
  1676. {
  1677. if (value is System.Web.UI.WebControls.Unit) {
  1678. System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
  1679. ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
  1680. BindingFlags.Instance | BindingFlags.Public,
  1681. null,
  1682. new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
  1683. null);
  1684. return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
  1685. }
  1686. if (value is System.Web.UI.WebControls.FontUnit) {
  1687. System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
  1688. Type cParamType = null;
  1689. object cParam = null;
  1690. switch (s.Type) {
  1691. case FontSize.AsUnit:
  1692. case FontSize.NotSet:
  1693. cParamType = typeof (System.Web.UI.WebControls.Unit);
  1694. cParam = s.Unit;
  1695. break;
  1696. default:
  1697. cParamType = typeof (string);
  1698. cParam = s.Type.ToString ();
  1699. break;
  1700. }
  1701. ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
  1702. BindingFlags.Instance | BindingFlags.Public,
  1703. null,
  1704. new Type[] {cParamType},
  1705. null);
  1706. if (c != null)
  1707. return new InstanceDescriptor (c, new object[] {cParam});
  1708. }
  1709. return null;
  1710. }
  1711. #if DEBUG
  1712. CodeMethodInvokeExpression CreateConsoleWriteLineCall (string format, params CodeExpression[] parms)
  1713. {
  1714. CodeMethodReferenceExpression cwl = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (System.Console)), "WriteLine");
  1715. CodeMethodInvokeExpression cwlCall = new CodeMethodInvokeExpression (cwl);
  1716. cwlCall.Parameters.Add (new CodePrimitiveExpression (format));
  1717. if (parms != null && parms.Length > 0)
  1718. foreach (CodeExpression expr in parms)
  1719. cwlCall.Parameters.Add (expr);
  1720. return cwlCall;
  1721. }
  1722. #endif
  1723. }
  1724. }