TemplateControlCompiler.cs 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104
  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*\)\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. CodeExpression CreateEvalInvokeExpression (Regex regex, string value, bool isBind)
  403. {
  404. Match match = regex.Match (value);
  405. if (!match.Success) {
  406. #if NET_2_0
  407. if (isBind)
  408. throw new HttpParseException ("Bind invocation wasn't formatted properly.");
  409. #endif
  410. return null;
  411. }
  412. string sanitizedSnippet;
  413. if (isBind)
  414. sanitizedSnippet = SanitizeBindCall (match);
  415. else
  416. sanitizedSnippet = value;
  417. return new CodeSnippetExpression (sanitizedSnippet);
  418. }
  419. string SanitizeBindCall (Match match)
  420. {
  421. GroupCollection groups = match.Groups;
  422. StringBuilder sb = new StringBuilder ("Eval(\"" + groups [1] + "\"");
  423. Group second = groups [2];
  424. if (second != null) {
  425. string v = second.Value;
  426. if (v != null && v.Length > 0)
  427. sb.Append (",\"" + second + "\"");
  428. }
  429. sb.Append (")");
  430. return sb.ToString ();
  431. }
  432. string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
  433. {
  434. value = TrimDB (value, true);
  435. CodeMemberMethod method;
  436. string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
  437. CodeExpression valueExpression = null;
  438. value = value.Trim ();
  439. #if NET_2_0
  440. bool need_if = false;
  441. if (StrUtils.StartsWith (value, "Bind", true)) {
  442. valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, true);
  443. if (valueExpression != null)
  444. need_if = true;
  445. } else
  446. #endif
  447. if (StrUtils.StartsWith (value, "Eval", true))
  448. valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, false);
  449. if (valueExpression == null)
  450. valueExpression = new CodeSnippetExpression (value);
  451. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
  452. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  453. // This should be a CodePropertyReferenceExpression for properties... but it works anyway
  454. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
  455. CodeExpression expr;
  456. if (type == typeof (string)) {
  457. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  458. CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
  459. tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
  460. tostring.Parameters.Add (valueExpression);
  461. expr = tostring;
  462. } else
  463. expr = new CodeCastExpression (type, valueExpression);
  464. CodeAssignStatement assign = new CodeAssignStatement (field, expr);
  465. #if NET_2_0
  466. if (need_if) {
  467. CodeExpression page = new CodePropertyReferenceExpression (thisRef, "Page");
  468. CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
  469. CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
  470. CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
  471. method.Statements.Add (ccs);
  472. }
  473. else
  474. #endif
  475. method.Statements.Add (assign);
  476. mainClass.Members.Add (method);
  477. return method.Name;
  478. }
  479. void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
  480. {
  481. CodeMemberMethod method = builder.method;
  482. bool isWritable = IsWritablePropertyOrField (member);
  483. if (isDataBound && isWritable) {
  484. string dbMethodName = DataBoundProperty (builder, type, var_name, att);
  485. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  486. return;
  487. }
  488. #if NET_2_0
  489. else if (isExpression && isWritable) {
  490. AddExpressionAssign (method, builder, member, type, var_name, att);
  491. return;
  492. }
  493. #endif
  494. CodeAssignStatement assign = new CodeAssignStatement ();
  495. assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
  496. currentLocation = builder.location;
  497. assign.Right = GetExpressionFromString (type, att, member);
  498. method.Statements.Add (AddLinePragma (assign, builder));
  499. }
  500. bool IsDirective (string value, char directiveChar)
  501. {
  502. if (value == null || value == String.Empty)
  503. return false;
  504. value = value.Trim ();
  505. if (!StrUtils.StartsWith (value, "<%") || !StrUtils.EndsWith (value, "%>"))
  506. return false;
  507. int dcIndex = value.IndexOf (directiveChar, 2);
  508. if (dcIndex == -1)
  509. return false;
  510. if (dcIndex == 2)
  511. return true;
  512. dcIndex--;
  513. while (dcIndex >= 2) {
  514. if (!Char.IsWhiteSpace (value [dcIndex]))
  515. return false;
  516. dcIndex--;
  517. }
  518. return true;
  519. }
  520. bool IsDataBound (string value)
  521. {
  522. return IsDirective (value, '#');
  523. }
  524. #if NET_2_0
  525. bool IsExpression (string value)
  526. {
  527. return IsDirective (value, '$');
  528. }
  529. void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
  530. {
  531. string str = TrimDB (value, false);
  532. if (StrUtils.StartsWith (str, "Bind", true)) {
  533. Match match = bindRegex.Match (str);
  534. if (match.Success) {
  535. string bindingName = match.Groups [1].Value;
  536. TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
  537. if (templateBuilder == null)
  538. throw new HttpException ("Bind expression not allowed in this context.");
  539. if (templateBuilder.BindingDirection == BindingDirection.OneWay)
  540. return;
  541. string id = builder.attribs ["ID"] as string;
  542. if (id == null)
  543. throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
  544. templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
  545. }
  546. }
  547. }
  548. #endif
  549. /*
  550. static bool InvariantCompare (string a, string b)
  551. {
  552. return (0 == String.Compare (a, b, false, CultureInfo.InvariantCulture));
  553. }
  554. */
  555. static bool InvariantCompareNoCase (string a, string b)
  556. {
  557. return (0 == String.Compare (a, b, true, CultureInfo.InvariantCulture));
  558. }
  559. static MemberInfo GetFieldOrProperty (Type type, string name)
  560. {
  561. MemberInfo member = null;
  562. try {
  563. member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
  564. } catch {}
  565. if (member != null)
  566. return member;
  567. try {
  568. member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
  569. } catch {}
  570. return member;
  571. }
  572. static bool IsWritablePropertyOrField (MemberInfo member)
  573. {
  574. PropertyInfo pi = member as PropertyInfo;
  575. if (pi != null)
  576. return pi.GetSetMethod (false) != null;
  577. FieldInfo fi = member as FieldInfo;
  578. if (fi != null)
  579. return !fi.IsInitOnly;
  580. throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
  581. }
  582. bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
  583. string attValue, string prefix)
  584. {
  585. int hyphen = id.IndexOf ('-');
  586. bool isPropertyInfo = (member is PropertyInfo);
  587. bool isDataBound = IsDataBound (attValue);
  588. #if NET_2_0
  589. bool isExpression = !isDataBound && IsExpression (attValue);
  590. #else
  591. bool isExpression = false;
  592. #endif
  593. Type type;
  594. if (isPropertyInfo) {
  595. type = ((PropertyInfo) member).PropertyType;
  596. } else {
  597. type = ((FieldInfo) member).FieldType;
  598. }
  599. if (InvariantCompareNoCase (member.Name, id)) {
  600. #if NET_2_0
  601. if (isDataBound)
  602. RegisterBindingInfo (builder, member.Name, ref attValue);
  603. #endif
  604. if (!IsWritablePropertyOrField (member))
  605. return false;
  606. AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
  607. return true;
  608. }
  609. if (hyphen == -1)
  610. return false;
  611. string prop_field = id.Replace ("-", ".");
  612. string [] parts = prop_field.Split (new char [] {'.'});
  613. int length = parts.Length;
  614. if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
  615. return false;
  616. if (length > 2) {
  617. MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
  618. if (sub_member == null)
  619. return false;
  620. string new_prefix = prefix + member.Name + ".";
  621. string new_id = id.Substring (hyphen + 1);
  622. return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
  623. }
  624. MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
  625. if (!(subpf is PropertyInfo))
  626. return false;
  627. PropertyInfo subprop = (PropertyInfo) subpf;
  628. if (subprop.CanWrite == false)
  629. return false;
  630. bool is_bool = (subprop.PropertyType == typeof (bool));
  631. if (!is_bool && attValue == null)
  632. return false; // Font-Size -> Font-Size="" as html
  633. string val = attValue;
  634. if (attValue == null && is_bool)
  635. val = "true"; // Font-Bold <=> Font-Bold="true"
  636. #if NET_2_0
  637. if (isDataBound)
  638. RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
  639. #endif
  640. AddCodeForPropertyOrField (builder, subprop.PropertyType,
  641. prefix + member.Name + "." + subprop.Name,
  642. val, subprop, isDataBound, isExpression);
  643. return true;
  644. }
  645. #if NET_2_0
  646. CodeExpression CompileExpression (MemberInfo member, Type type, string value, bool useSetAttribute)
  647. {
  648. // First let's find the correct expression builder
  649. value = value.Substring (3, value.Length - 5).Trim ();
  650. int colon = value.IndexOf (':');
  651. if (colon == -1)
  652. return null;
  653. string prefix = value.Substring (0, colon).Trim ();
  654. string expr = value.Substring (colon + 1).Trim ();
  655. System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration ("");
  656. if (config == null)
  657. return null;
  658. CompilationSection cs = (CompilationSection)config.GetSection ("system.web/compilation");
  659. if (cs == null)
  660. return null;
  661. if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
  662. return null;
  663. System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
  664. if (ceb == null)
  665. return null;
  666. string builderType = ceb.Type;
  667. Type t;
  668. try {
  669. t = HttpApplication.LoadType (builderType, true);
  670. } catch (Exception e) {
  671. throw new HttpException (String.Format ("Failed to load expression builder type `{0}'", builderType), e);
  672. }
  673. if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
  674. throw new HttpException (String.Format ("Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder", builderType));
  675. System.Web.Compilation.ExpressionBuilder eb = null;
  676. object parsedData;
  677. ExpressionBuilderContext ctx;
  678. try {
  679. eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
  680. ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
  681. parsedData = eb.ParseExpression (expr, type, ctx);
  682. } catch (Exception e) {
  683. throw new HttpException (String.Format ("Failed to create an instance of type `{0}'", builderType), e);
  684. }
  685. BoundPropertyEntry bpe = CreateBoundPropertyEntry (member as PropertyInfo, prefix, expr, useSetAttribute);
  686. return eb.GetCodeExpression (bpe, parsedData, ctx);
  687. }
  688. void AddExpressionAssign (CodeMemberMethod method, ControlBuilder builder, MemberInfo member, Type type, string name, string value)
  689. {
  690. CodeExpression expr = CompileExpression (member, type, value, false);
  691. if (expr == null)
  692. return;
  693. CodeAssignStatement assign = new CodeAssignStatement ();
  694. assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
  695. assign.Right = expr;
  696. builder.method.Statements.Add (AddLinePragma (assign, builder));
  697. }
  698. BoundPropertyEntry CreateBoundPropertyEntry (PropertyInfo pi, string prefix, string expr, bool useSetAttribute)
  699. {
  700. BoundPropertyEntry ret = new BoundPropertyEntry ();
  701. ret.Expression = expr;
  702. ret.ExpressionPrefix = prefix;
  703. ret.Generated = false;
  704. if (pi != null) {
  705. ret.Name = pi.Name;
  706. ret.PropertyInfo = pi;
  707. ret.Type = pi.PropertyType;
  708. }
  709. ret.UseSetAttribute = useSetAttribute;
  710. return ret;
  711. }
  712. void AssignPropertyFromResources (ControlBuilder builder, MemberInfo mi, string attvalue)
  713. {
  714. bool isProperty = mi.MemberType == MemberTypes.Property;
  715. bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
  716. if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
  717. return;
  718. string memberName = mi.Name;
  719. string resname = String.Concat (attvalue, ".", memberName);
  720. // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
  721. string inputFile = parser.InputFile;
  722. string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
  723. if (StrUtils.StartsWith (inputFile, physPath))
  724. inputFile = parser.InputFile.Substring (physPath.Length - 1);
  725. else
  726. return;
  727. char dsc = System.IO.Path.DirectorySeparatorChar;
  728. if (dsc != '/')
  729. inputFile = inputFile.Replace (dsc, '/');
  730. object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
  731. if (obj == null)
  732. return;
  733. if (!isProperty && !isField)
  734. return; // an "impossible" case
  735. CodeAssignStatement assign = new CodeAssignStatement ();
  736. assign.Left = new CodePropertyReferenceExpression (ctrlVar, memberName);
  737. assign.Right = ResourceExpressionBuilder.CreateGetLocalResourceObject (mi, resname);
  738. builder.method.Statements.Add (AddLinePragma (assign, builder));
  739. }
  740. void AssignPropertiesFromResources (ControlBuilder builder, Type controlType, string attvalue)
  741. {
  742. // Process all public fields and properties of the control. We don't use GetMembers to make the code
  743. // faster
  744. FieldInfo [] fields = controlType.GetFields (
  745. BindingFlags.Instance | BindingFlags.Static |
  746. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  747. PropertyInfo [] properties = controlType.GetProperties (
  748. BindingFlags.Instance | BindingFlags.Static |
  749. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  750. foreach (FieldInfo fi in fields)
  751. AssignPropertyFromResources (builder, fi, attvalue);
  752. foreach (PropertyInfo pi in properties)
  753. AssignPropertyFromResources (builder, pi, attvalue);
  754. }
  755. void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
  756. {
  757. if (attvalue == null || attvalue.Length == 0)
  758. return;
  759. Type controlType = builder.ControlType;
  760. if (controlType == null)
  761. return;
  762. AssignPropertiesFromResources (builder, controlType, attvalue);
  763. }
  764. #endif
  765. void AddEventAssign (CodeMemberMethod method, ControlBuilder builder, string name, Type type, string value)
  766. {
  767. //"__ctrl.{0} += new {1} (this.{2});"
  768. CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
  769. CodeDelegateCreateExpression create;
  770. create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
  771. CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
  772. method.Statements.Add (attach);
  773. }
  774. void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
  775. {
  776. EventInfo [] ev_info = null;
  777. Type type = builder.ControlType;
  778. string attvalue = builder.attribs [id] as string;
  779. if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
  780. if (ev_info == null)
  781. ev_info = type.GetEvents ();
  782. string id_as_event = id.Substring (2);
  783. foreach (EventInfo ev in ev_info){
  784. if (InvariantCompareNoCase (ev.Name, id_as_event)){
  785. AddEventAssign (builder.method,
  786. builder,
  787. ev.Name,
  788. ev.EventHandlerType,
  789. attvalue);
  790. return;
  791. }
  792. }
  793. }
  794. #if NET_2_0
  795. if (id.ToLower () == "meta:resourcekey") {
  796. AssignPropertiesFromResources (builder, attvalue);
  797. return;
  798. }
  799. #endif
  800. int hyphen = id.IndexOf ('-');
  801. string alt_id = id;
  802. if (hyphen != -1)
  803. alt_id = id.Substring (0, hyphen);
  804. MemberInfo fop = GetFieldOrProperty (type, alt_id);
  805. if (fop != null) {
  806. if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
  807. return;
  808. }
  809. if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
  810. throw new ParseException (builder.location, "Unrecognized attribute: " + id);
  811. CodeMemberMethod method = builder.method;
  812. bool isDatabound = IsDataBound (attvalue);
  813. #if NET_2_0
  814. bool isExpression = !isDatabound && IsExpression (attvalue);
  815. #endif
  816. if (isDatabound) {
  817. string value = attvalue.Substring (3, attvalue.Length - 5).Trim ();
  818. CodeExpression valueExpression = null;
  819. #if NET_2_0
  820. if (StrUtils.StartsWith (value, "Bind", true))
  821. valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, true);
  822. else
  823. #endif
  824. if (StrUtils.StartsWith (value, "Eval", true))
  825. valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, false);
  826. if (valueExpression == null && value != null && value.Trim () != String.Empty)
  827. valueExpression = new CodeSnippetExpression (value);
  828. CreateDBAttributeMethod (builder, id, valueExpression);
  829. } else {
  830. CodeCastExpression cast;
  831. CodeMethodReferenceExpression methodExpr;
  832. CodeMethodInvokeExpression expr;
  833. cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
  834. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  835. expr = new CodeMethodInvokeExpression (methodExpr);
  836. expr.Parameters.Add (new CodePrimitiveExpression (id));
  837. CodeExpression valueExpr = null;
  838. #if NET_2_0
  839. if (isExpression)
  840. valueExpr = CompileExpression (null, typeof (string), attvalue, true);
  841. if (valueExpr == null)
  842. #endif
  843. valueExpr = new CodePrimitiveExpression (attvalue);
  844. expr.Parameters.Add (valueExpr);
  845. method.Statements.Add (AddLinePragma (expr, builder));
  846. }
  847. }
  848. protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
  849. {
  850. this.dataBoundAtts = 0;
  851. IDictionary atts = builder.attribs;
  852. if (atts == null || atts.Count == 0)
  853. return;
  854. foreach (string id in atts.Keys) {
  855. if (InvariantCompareNoCase (id, "runat"))
  856. continue;
  857. // ID is assigned in BuildControltree
  858. if (InvariantCompareNoCase (id, "id"))
  859. continue;
  860. #if NET_2_0
  861. /* we skip SkinID here as it's assigned in BuildControlTree */
  862. if (InvariantCompareNoCase (id, "skinid"))
  863. continue;
  864. if (InvariantCompareNoCase (id, "meta:resourcekey"))
  865. continue; // ignore, this one's processed at the very end of
  866. // the method
  867. #endif
  868. CreateAssignStatementFromAttribute (builder, id);
  869. }
  870. }
  871. void CreateDBAttributeMethod (ControlBuilder builder, string attr, CodeExpression code)
  872. {
  873. if (code == null)
  874. return;
  875. string id = builder.GetNextID (null);
  876. string dbMethodName = "__DataBind_" + id;
  877. CodeMemberMethod method = builder.method;
  878. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  879. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
  880. CodeCastExpression cast;
  881. CodeMethodReferenceExpression methodExpr;
  882. CodeMethodInvokeExpression expr;
  883. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  884. cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
  885. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  886. expr = new CodeMethodInvokeExpression (methodExpr);
  887. expr.Parameters.Add (new CodePrimitiveExpression (attr));
  888. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  889. tostring.Method = new CodeMethodReferenceExpression (
  890. new CodeTypeReferenceExpression (typeof (Convert)),
  891. "ToString");
  892. tostring.Parameters.Add (code);
  893. expr.Parameters.Add (tostring);
  894. method.Statements.Add (expr);
  895. mainClass.Members.Add (method);
  896. }
  897. void AddRenderControl (ControlBuilder builder)
  898. {
  899. CodeIndexerExpression indexer = new CodeIndexerExpression ();
  900. indexer.TargetObject = new CodePropertyReferenceExpression (
  901. new CodeArgumentReferenceExpression ("parameterContainer"),
  902. "Controls");
  903. indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
  904. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
  905. invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
  906. builder.renderMethod.Statements.Add (invoke);
  907. builder.renderIndex++;
  908. }
  909. protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
  910. {
  911. if (parent == null || child == null)
  912. return;
  913. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
  914. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
  915. object [] atts = null;
  916. if (child.ControlType != null)
  917. atts = child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
  918. if (atts != null && atts.Length > 0) {
  919. PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
  920. CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
  921. CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
  922. build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
  923. build.Parameters.Add (new CodePrimitiveExpression (child.ID));
  924. #if NET_1_1
  925. if (pca.Shared)
  926. build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
  927. else
  928. #endif
  929. build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
  930. build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
  931. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
  932. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
  933. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
  934. build.Parameters.Add (new CodeDelegateCreateExpression (
  935. new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
  936. thisRef, child.method.Name));
  937. parent.methodStatements.Add (AddLinePragma (build, parent));
  938. if (parent.HasAspCode)
  939. AddRenderControl (parent);
  940. return;
  941. }
  942. if (child.isProperty || parent.ChildrenAsProperties) {
  943. expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
  944. parent.methodStatements.Add (AddLinePragma (expr, parent));
  945. return;
  946. }
  947. parent.methodStatements.Add (AddLinePragma (expr, parent));
  948. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
  949. if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType))
  950. AddParsedSubObjectStmt (parent, field);
  951. else {
  952. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
  953. invoke.Parameters.Add (field);
  954. parent.methodStatements.Add (AddLinePragma (invoke, parent));
  955. }
  956. if (parent.HasAspCode)
  957. AddRenderControl (parent);
  958. }
  959. void AddTemplateInvocation (ControlBuilder builder, string name, string methodName)
  960. {
  961. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  962. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  963. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  964. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  965. newCompiled.Parameters.Add (newBuild);
  966. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  967. builder.method.Statements.Add (AddLinePragma (assign, builder));
  968. }
  969. #if NET_2_0
  970. void AddBindableTemplateInvocation (ControlBuilder builder, string name, string methodName, string extractMethodName)
  971. {
  972. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  973. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  974. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  975. CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
  976. new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);
  977. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
  978. newCompiled.Parameters.Add (newBuild);
  979. newCompiled.Parameters.Add (newExtract);
  980. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  981. builder.method.Statements.Add (AddLinePragma (assign, builder));
  982. }
  983. string CreateExtractValuesMethod (TemplateBuilder builder)
  984. {
  985. CodeMemberMethod method = new CodeMemberMethod ();
  986. method.Name = "__ExtractValues_" + builder.ID;
  987. method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  988. method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
  989. CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
  990. arg.Type = new CodeTypeReference (typeof (Control));
  991. arg.Name = "__container";
  992. method.Parameters.Add (arg);
  993. mainClass.Members.Add (method);
  994. CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
  995. newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
  996. method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
  997. CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
  998. if (builder.Bindings != null) {
  999. Hashtable hash = new Hashtable ();
  1000. foreach (TemplateBinding binding in builder.Bindings) {
  1001. CodeConditionStatement sif;
  1002. CodeVariableReferenceExpression control;
  1003. CodeAssignStatement assign;
  1004. if (hash [binding.ControlId] == null) {
  1005. CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
  1006. method.Statements.Add (dec);
  1007. CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
  1008. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
  1009. invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
  1010. assign = new CodeAssignStatement ();
  1011. control = new CodeVariableReferenceExpression (binding.ControlId);
  1012. assign.Left = control;
  1013. assign.Right = new CodeCastExpression (binding.ControlType, invoke);
  1014. method.Statements.Add (assign);
  1015. sif = new CodeConditionStatement ();
  1016. sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
  1017. method.Statements.Add (sif);
  1018. hash [binding.ControlId] = sif;
  1019. }
  1020. sif = (CodeConditionStatement) hash [binding.ControlId];
  1021. control = new CodeVariableReferenceExpression (binding.ControlId);
  1022. assign = new CodeAssignStatement ();
  1023. assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
  1024. assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
  1025. sif.TrueStatements.Add (assign);
  1026. }
  1027. }
  1028. method.Statements.Add (new CodeMethodReturnStatement (tableExp));
  1029. return method.Name;
  1030. }
  1031. void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
  1032. {
  1033. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  1034. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  1035. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  1036. newCompiled.Parameters.Add (newBuild);
  1037. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
  1038. invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
  1039. invoke.Parameters.Add (newCompiled);
  1040. method.Statements.Add (AddLinePragma (invoke, cbuilder));
  1041. }
  1042. #endif
  1043. void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
  1044. {
  1045. if (cr.Code == null || cr.Code.Trim () == "")
  1046. return;
  1047. if (!cr.IsAssign) {
  1048. CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
  1049. parent.renderMethod.Statements.Add (AddLinePragma (code, cr));
  1050. return;
  1051. }
  1052. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
  1053. expr.Method = new CodeMethodReferenceExpression (
  1054. new CodeArgumentReferenceExpression ("__output"),
  1055. "Write");
  1056. expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
  1057. parent.renderMethod.Statements.Add (AddLinePragma (expr, cr));
  1058. }
  1059. static PropertyInfo GetContainerProperty (Type type, string[] propNames)
  1060. {
  1061. PropertyInfo prop;
  1062. foreach (string name in propNames) {
  1063. prop = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
  1064. if (prop != null)
  1065. return prop;
  1066. }
  1067. return null;
  1068. }
  1069. #if !NET_2_0
  1070. static string[] containerPropNames = {"Items", "Rows"};
  1071. #endif
  1072. static Type GetContainerType (ControlBuilder builder)
  1073. {
  1074. Type type = builder.BindingContainerType;
  1075. #if NET_2_0
  1076. return type;
  1077. #else
  1078. PropertyInfo prop = GetContainerProperty (type, containerPropNames);
  1079. if (prop == null)
  1080. return type;
  1081. Type ptype = prop.PropertyType;
  1082. if (!typeof (ICollection).IsAssignableFrom (ptype))
  1083. return type;
  1084. prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
  1085. if (prop == null)
  1086. return type;
  1087. return prop.PropertyType;
  1088. #endif
  1089. }
  1090. CodeMemberMethod CreateDBMethod (ControlBuilder builder, string name, Type container, Type target)
  1091. {
  1092. CodeMemberMethod method = new CodeMemberMethod ();
  1093. method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  1094. method.Name = name;
  1095. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
  1096. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
  1097. CodeTypeReference containerRef = new CodeTypeReference (container);
  1098. CodeTypeReference targetRef = new CodeTypeReference (target);
  1099. CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
  1100. decl.Name = "Container";
  1101. decl.Type = containerRef;
  1102. method.Statements.Add (decl);
  1103. decl = new CodeVariableDeclarationStatement();
  1104. decl.Name = "target";
  1105. decl.Type = targetRef;
  1106. method.Statements.Add (decl);
  1107. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  1108. CodeAssignStatement assign = new CodeAssignStatement ();
  1109. assign.Left = targetExpr;
  1110. assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
  1111. method.Statements.Add (AddLinePragma (assign, builder));
  1112. assign = new CodeAssignStatement ();
  1113. assign.Left = new CodeVariableReferenceExpression ("Container");
  1114. assign.Right = new CodeCastExpression (containerRef,
  1115. new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
  1116. method.Statements.Add (AddLinePragma (assign, builder));
  1117. return method;
  1118. }
  1119. void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
  1120. {
  1121. if (db.Code == null || db.Code.Trim () == "")
  1122. return;
  1123. EnsureID (db);
  1124. CreateField (db, false);
  1125. string dbMethodName = "__DataBind_" + db.ID;
  1126. // Add the method that builds the DataBoundLiteralControl
  1127. InitMethod (db, false, false);
  1128. CodeMemberMethod method = db.method;
  1129. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  1130. method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  1131. // Add the DataBind handler
  1132. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
  1133. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  1134. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  1135. invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
  1136. invoke.Parameters.Add (new CodePrimitiveExpression (0));
  1137. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  1138. tostring.Method = new CodeMethodReferenceExpression (
  1139. new CodeTypeReferenceExpression (typeof (Convert)),
  1140. "ToString");
  1141. tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
  1142. invoke.Parameters.Add (tostring);
  1143. method.Statements.Add (AddLinePragma (invoke, builder));
  1144. mainClass.Members.Add (method);
  1145. AddChildCall (builder, db);
  1146. }
  1147. void FlushText (ControlBuilder builder, StringBuilder sb)
  1148. {
  1149. if (sb.Length > 0) {
  1150. AddLiteralSubObject (builder, sb.ToString ());
  1151. sb.Length = 0;
  1152. }
  1153. }
  1154. protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
  1155. {
  1156. EnsureID (builder);
  1157. bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
  1158. if (!isTemplate && !inTemplate) {
  1159. CreateField (builder, true);
  1160. } else if (!isTemplate) {
  1161. bool doCheck = false;
  1162. #if NET_2_0
  1163. bool singleInstance = false;
  1164. ControlBuilder pb = builder.parentBuilder;
  1165. TemplateBuilder tpb;
  1166. while (pb != null) {
  1167. tpb = pb as TemplateBuilder;
  1168. if (tpb == null) {
  1169. pb = pb.parentBuilder;
  1170. continue;
  1171. }
  1172. if (tpb.TemplateInstance == TemplateInstance.Single)
  1173. singleInstance = true;
  1174. break;
  1175. }
  1176. if (!singleInstance)
  1177. #endif
  1178. builder.ID = builder.GetNextID (null);
  1179. #if NET_2_0
  1180. else
  1181. doCheck = true;
  1182. #endif
  1183. CreateField (builder, doCheck);
  1184. }
  1185. InitMethod (builder, isTemplate, childrenAsProperties);
  1186. if (!isTemplate || builder.GetType () == typeof (RootBuilder))
  1187. CreateAssignStatementsFromAttributes (builder);
  1188. if (builder.Children != null && builder.Children.Count > 0) {
  1189. StringBuilder sb = new StringBuilder ();
  1190. foreach (object b in builder.Children) {
  1191. if (b is string) {
  1192. sb.Append ((string) b);
  1193. continue;
  1194. }
  1195. FlushText (builder, sb);
  1196. if (b is ObjectTagBuilder) {
  1197. ProcessObjectTag ((ObjectTagBuilder) b);
  1198. continue;
  1199. }
  1200. StringPropertyBuilder pb = b as StringPropertyBuilder;
  1201. if (pb != null){
  1202. if (pb.Children != null && pb.Children.Count > 0) {
  1203. StringBuilder asb = new StringBuilder ();
  1204. foreach (string s in pb.Children)
  1205. asb.Append (s);
  1206. CodeMemberMethod method = builder.method;
  1207. CodeAssignStatement assign = new CodeAssignStatement ();
  1208. assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
  1209. assign.Right = new CodePrimitiveExpression (asb.ToString ());
  1210. method.Statements.Add (AddLinePragma (assign, builder));
  1211. }
  1212. continue;
  1213. }
  1214. #if NET_2_0
  1215. if (b is ContentBuilderInternal) {
  1216. ContentBuilderInternal cb = (ContentBuilderInternal) b;
  1217. CreateControlTree (cb, false, true);
  1218. AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
  1219. continue;
  1220. }
  1221. #endif
  1222. // Ignore TemplateBuilders - they are processed in InitMethod
  1223. if (b is TemplateBuilder)
  1224. continue;
  1225. if (b is CodeRenderBuilder) {
  1226. AddCodeRender (builder, (CodeRenderBuilder) b);
  1227. continue;
  1228. }
  1229. if (b is DataBindingBuilder) {
  1230. AddDataBindingLiteral (builder, (DataBindingBuilder) b);
  1231. continue;
  1232. }
  1233. if (b is ControlBuilder) {
  1234. ControlBuilder child = (ControlBuilder) b;
  1235. CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
  1236. AddChildCall (builder, child);
  1237. continue;
  1238. }
  1239. throw new Exception ("???");
  1240. }
  1241. FlushText (builder, sb);
  1242. }
  1243. if (builder.defaultPropertyBuilder != null) {
  1244. ControlBuilder b = builder.defaultPropertyBuilder;
  1245. CreateControlTree (b, false, true);
  1246. AddChildCall (builder, b);
  1247. }
  1248. if (builder.HasAspCode) {
  1249. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1250. m.TargetObject = thisRef;
  1251. m.MethodName = builder.renderMethod.Name;
  1252. CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
  1253. create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
  1254. create.TargetObject = thisRef;
  1255. create.MethodName = builder.renderMethod.Name;
  1256. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  1257. invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
  1258. invoke.Parameters.Add (create);
  1259. builder.methodStatements.Add (invoke);
  1260. }
  1261. #if NET_2_0
  1262. if (builder is RootBuilder)
  1263. if (!String.IsNullOrEmpty (parser.MetaResourceKey))
  1264. AssignPropertiesFromResources (builder, parser.BaseType, parser.MetaResourceKey);
  1265. if ((!isTemplate || builder is RootBuilder) && builder.attribs != null && builder.attribs ["meta:resourcekey"] != null)
  1266. CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
  1267. #endif
  1268. if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
  1269. builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  1270. }
  1271. protected internal override void CreateMethods ()
  1272. {
  1273. base.CreateMethods ();
  1274. CreateProperties ();
  1275. CreateControlTree (parser.RootBuilder, false, false);
  1276. CreateFrameworkInitializeMethod ();
  1277. }
  1278. #if NET_2_0
  1279. void CallBaseFrameworkInitialize (CodeMemberMethod method)
  1280. {
  1281. CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
  1282. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
  1283. method.Statements.Add (invoke);
  1284. }
  1285. #endif
  1286. void CallSetStringResourcePointer (CodeMemberMethod method)
  1287. {
  1288. CodeFieldReferenceExpression stringResource = GetMainClassFieldReferenceExpression ("__stringResource");
  1289. method.Statements.Add (
  1290. new CodeMethodInvokeExpression (
  1291. thisRef,
  1292. "SetStringResourcePointer",
  1293. new CodeExpression[] {stringResource, new CodePrimitiveExpression (0)})
  1294. );
  1295. }
  1296. void CreateFrameworkInitializeMethod ()
  1297. {
  1298. CodeMemberMethod method = new CodeMemberMethod ();
  1299. method.Name = "FrameworkInitialize";
  1300. method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1301. PrependStatementsToFrameworkInitialize (method);
  1302. #if NET_2_0
  1303. CallBaseFrameworkInitialize (method);
  1304. #endif
  1305. CallSetStringResourcePointer (method);
  1306. AppendStatementsToFrameworkInitialize (method);
  1307. mainClass.Members.Add (method);
  1308. }
  1309. protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
  1310. {
  1311. }
  1312. protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
  1313. {
  1314. if (!parser.EnableViewState) {
  1315. CodeAssignStatement stmt = new CodeAssignStatement ();
  1316. stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
  1317. stmt.Right = new CodePrimitiveExpression (false);
  1318. method.Statements.Add (stmt);
  1319. }
  1320. CodeMethodReferenceExpression methodExpr;
  1321. methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
  1322. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
  1323. method.Statements.Add (new CodeExpressionStatement (expr));
  1324. }
  1325. protected override void AddApplicationAndSessionObjects ()
  1326. {
  1327. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
  1328. CreateFieldForObject (tag.Type, tag.ObjectID);
  1329. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
  1330. }
  1331. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
  1332. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
  1333. }
  1334. }
  1335. protected override void CreateStaticFields ()
  1336. {
  1337. base.CreateStaticFields ();
  1338. CodeMemberField fld = new CodeMemberField (typeof (object), "__stringResource");
  1339. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  1340. fld.InitExpression = new CodePrimitiveExpression (null);
  1341. mainClass.Members.Add (fld);
  1342. }
  1343. protected void ProcessObjectTag (ObjectTagBuilder tag)
  1344. {
  1345. string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
  1346. CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
  1347. }
  1348. void CreateProperties ()
  1349. {
  1350. if (!parser.AutoEventWireup) {
  1351. CreateAutoEventWireup ();
  1352. } else {
  1353. CreateAutoHandlers ();
  1354. }
  1355. CreateApplicationInstance ();
  1356. }
  1357. void CreateApplicationInstance ()
  1358. {
  1359. CodeMemberProperty prop = new CodeMemberProperty ();
  1360. Type appType = typeof (HttpApplication);
  1361. prop.Type = new CodeTypeReference (appType);
  1362. prop.Name = "ApplicationInstance";
  1363. prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
  1364. CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
  1365. propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
  1366. CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
  1367. prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
  1368. #if NET_2_0
  1369. if (partialClass != null)
  1370. partialClass.Members.Add (prop);
  1371. else
  1372. #endif
  1373. mainClass.Members.Add (prop);
  1374. }
  1375. void CreateAutoHandlers ()
  1376. {
  1377. // Create AutoHandlers property
  1378. CodeMemberProperty prop = new CodeMemberProperty ();
  1379. prop.Type = new CodeTypeReference (typeof (int));
  1380. prop.Name = "AutoHandlers";
  1381. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1382. CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
  1383. CodeFieldReferenceExpression fldRef ;
  1384. fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
  1385. ret.Expression = fldRef;
  1386. prop.GetStatements.Add (ret);
  1387. prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
  1388. #if NET_2_0
  1389. CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
  1390. prop.CustomAttributes.Add (attr);
  1391. #endif
  1392. mainClass.Members.Add (prop);
  1393. // Add the __autoHandlers field
  1394. CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
  1395. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  1396. mainClass.Members.Add (fld);
  1397. }
  1398. void CreateAutoEventWireup ()
  1399. {
  1400. // The getter returns false
  1401. CodeMemberProperty prop = new CodeMemberProperty ();
  1402. prop.Type = new CodeTypeReference (typeof (bool));
  1403. prop.Name = "SupportAutoEvents";
  1404. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1405. prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
  1406. mainClass.Members.Add (prop);
  1407. }
  1408. #if NET_2_0
  1409. protected virtual string HandleUrlProperty (string str, MemberInfo member)
  1410. {
  1411. return str;
  1412. }
  1413. #endif
  1414. TypeConverter GetConverterForMember (MemberInfo member)
  1415. {
  1416. TypeConverterAttribute tca = null;
  1417. object[] attrs;
  1418. #if NET_2_0
  1419. attrs = member.GetCustomAttributes (typeof (TypeConverterAttribute), true);
  1420. if (attrs.Length > 0)
  1421. tca = attrs [0] as TypeConverterAttribute;
  1422. #else
  1423. attrs = member.GetCustomAttributes (true);
  1424. foreach (object attr in attrs) {
  1425. tca = attr as TypeConverterAttribute;
  1426. if (tca != null)
  1427. break;
  1428. }
  1429. #endif
  1430. if (tca == null)
  1431. return null;
  1432. string typeName = tca.ConverterTypeName;
  1433. if (typeName == null || typeName.Length == 0)
  1434. return null;
  1435. Type t = null;
  1436. try {
  1437. t = HttpApplication.LoadType (typeName);
  1438. } catch (Exception) {
  1439. // ignore
  1440. }
  1441. if (t == null)
  1442. return null;
  1443. return (TypeConverter) Activator.CreateInstance (t);
  1444. }
  1445. CodeExpression CreateNullableExpression (Type type, CodeExpression inst, bool nullable)
  1446. {
  1447. #if NET_2_0
  1448. if (!nullable)
  1449. return inst;
  1450. return new CodeObjectCreateExpression (
  1451. type,
  1452. new CodeExpression[] {inst}
  1453. );
  1454. #else
  1455. return inst;
  1456. #endif
  1457. }
  1458. bool SafeCanConvertFrom (Type type, TypeConverter cvt)
  1459. {
  1460. try {
  1461. return cvt.CanConvertFrom (type);
  1462. } catch (NotImplementedException) {
  1463. return false;
  1464. }
  1465. }
  1466. bool SafeCanConvertTo (Type type, TypeConverter cvt)
  1467. {
  1468. try {
  1469. return cvt.CanConvertTo (type);
  1470. } catch (NotImplementedException) {
  1471. return false;
  1472. }
  1473. }
  1474. CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
  1475. {
  1476. TypeConverter cvt = GetConverterForMember (member);
  1477. if (cvt != null && !SafeCanConvertFrom (typeof (string), cvt))
  1478. cvt = null;
  1479. object convertedFromAttr = null;
  1480. bool preConverted = false;
  1481. if (cvt != null && str != null) {
  1482. convertedFromAttr = cvt.ConvertFromInvariantString (str);
  1483. if (convertedFromAttr != null) {
  1484. type = convertedFromAttr.GetType ();
  1485. preConverted = true;
  1486. }
  1487. }
  1488. bool wasNullable = false;
  1489. Type originalType = type;
  1490. #if NET_2_0
  1491. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
  1492. Type[] types = type.GetGenericArguments();
  1493. originalType = type;
  1494. type = types[0]; // we're interested only in the first type here
  1495. wasNullable = true;
  1496. }
  1497. #endif
  1498. if (type == typeof (string)) {
  1499. if (preConverted)
  1500. return CreateNullableExpression (originalType,
  1501. new CodePrimitiveExpression ((string) convertedFromAttr),
  1502. wasNullable);
  1503. #if NET_2_0
  1504. object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
  1505. if (urlAttr.Length != 0)
  1506. str = HandleUrlProperty (str, member);
  1507. #endif
  1508. return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
  1509. } else if (type == typeof (bool)) {
  1510. if (preConverted)
  1511. return CreateNullableExpression (originalType,
  1512. new CodePrimitiveExpression ((bool) convertedFromAttr),
  1513. wasNullable);
  1514. if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
  1515. return CreateNullableExpression (originalType, new CodePrimitiveExpression (true), wasNullable);
  1516. else if (InvariantCompareNoCase (str, "false"))
  1517. return CreateNullableExpression (originalType, new CodePrimitiveExpression (false), wasNullable);
  1518. #if NET_2_0
  1519. else if (wasNullable && InvariantCompareNoCase(str, "null"))
  1520. return new CodePrimitiveExpression (null);
  1521. #endif
  1522. else
  1523. throw new ParseException (currentLocation,
  1524. "Value '" + str + "' is not a valid boolean.");
  1525. } else if (type == monoTypeType)
  1526. type = typeof (System.Type);
  1527. if (str == null)
  1528. return new CodePrimitiveExpression (null);
  1529. if (type.IsPrimitive)
  1530. return CreateNullableExpression (originalType,
  1531. new CodePrimitiveExpression (
  1532. Convert.ChangeType (preConverted ? convertedFromAttr : str,
  1533. type, CultureInfo.InvariantCulture)),
  1534. wasNullable);
  1535. if (type == typeof (string [])) {
  1536. string [] subs;
  1537. if (preConverted)
  1538. subs = (string[])convertedFromAttr;
  1539. else
  1540. subs = str.Split (',');
  1541. CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
  1542. expr.CreateType = new CodeTypeReference (typeof (string));
  1543. foreach (string v in subs)
  1544. expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
  1545. return CreateNullableExpression (originalType, expr, wasNullable);
  1546. }
  1547. if (type == typeof (Color)) {
  1548. Color c;
  1549. if (!preConverted) {
  1550. if (colorConverter == null)
  1551. colorConverter = TypeDescriptor.GetConverter (typeof (Color));
  1552. if (str.Trim().Length == 0) {
  1553. CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
  1554. return CreateNullableExpression (originalType,
  1555. new CodeFieldReferenceExpression (ft, "Empty"),
  1556. wasNullable);
  1557. }
  1558. try {
  1559. if (str.IndexOf (',') == -1) {
  1560. c = (Color) colorConverter.ConvertFromString (str);
  1561. } else {
  1562. int [] argb = new int [4];
  1563. argb [0] = 255;
  1564. string [] parts = str.Split (',');
  1565. int length = parts.Length;
  1566. if (length < 3)
  1567. throw new Exception ();
  1568. int basei = (length == 4) ? 0 : 1;
  1569. for (int i = length - 1; i >= 0; i--) {
  1570. argb [basei + i] = (int) Byte.Parse (parts [i]);
  1571. }
  1572. c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
  1573. }
  1574. } catch (Exception e) {
  1575. // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
  1576. // TypeConverter for Color fails to ConvertFromString.
  1577. // Hence this hack...
  1578. if (InvariantCompareNoCase ("LightGrey", str)) {
  1579. c = Color.LightGray;
  1580. } else {
  1581. throw new ParseException (currentLocation,
  1582. "Color " + str + " is not a valid color.", e);
  1583. }
  1584. }
  1585. } else
  1586. c = (Color)convertedFromAttr;
  1587. if (c.IsKnownColor) {
  1588. CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
  1589. if (c.IsSystemColor)
  1590. type = typeof (SystemColors);
  1591. expr.TargetObject = new CodeTypeReferenceExpression (type);
  1592. expr.FieldName = c.Name;
  1593. return CreateNullableExpression (originalType, expr, wasNullable);
  1594. } else {
  1595. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1596. m.TargetObject = new CodeTypeReferenceExpression (type);
  1597. m.MethodName = "FromArgb";
  1598. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  1599. invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
  1600. invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
  1601. invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
  1602. invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
  1603. return CreateNullableExpression (originalType, invoke, wasNullable);
  1604. }
  1605. }
  1606. TypeConverter converter = preConverted ? cvt :
  1607. wasNullable ? TypeDescriptor.GetConverter (type) :
  1608. TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
  1609. if (preConverted || (converter != null && SafeCanConvertFrom (typeof (string), converter))) {
  1610. object value = preConverted ? convertedFromAttr : converter.ConvertFromInvariantString (str);
  1611. if (SafeCanConvertTo (typeof (InstanceDescriptor), converter)) {
  1612. InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
  1613. if (wasNullable)
  1614. return CreateNullableExpression (originalType, GenerateInstance (idesc, true),
  1615. wasNullable);
  1616. return new CodeCastExpression (type, GenerateInstance (idesc, true));
  1617. }
  1618. CodeExpression exp = GenerateObjectInstance (value, false);
  1619. if (exp != null)
  1620. return CreateNullableExpression (originalType, exp, wasNullable);
  1621. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1622. m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
  1623. m.MethodName = "GetConverter";
  1624. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  1625. CodeTypeReference tref = new CodeTypeReference (type);
  1626. invoke.Parameters.Add (new CodeTypeOfExpression (tref));
  1627. invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
  1628. invoke.Parameters.Add (new CodePrimitiveExpression (str));
  1629. if (wasNullable)
  1630. return CreateNullableExpression (originalType, invoke, wasNullable);
  1631. return new CodeCastExpression (type, invoke);
  1632. }
  1633. Console.WriteLine ("Unknown type: " + type + " value: " + str);
  1634. return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
  1635. }
  1636. CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
  1637. {
  1638. CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
  1639. int n = 0;
  1640. foreach (object ob in idesc.Arguments) {
  1641. CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
  1642. if (exp == null) return null;
  1643. parameters [n++] = exp;
  1644. }
  1645. switch (idesc.MemberInfo.MemberType) {
  1646. case MemberTypes.Constructor:
  1647. CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
  1648. return new CodeObjectCreateExpression (tob, parameters);
  1649. case MemberTypes.Method:
  1650. CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1651. return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
  1652. case MemberTypes.Field:
  1653. CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1654. return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
  1655. case MemberTypes.Property:
  1656. CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1657. return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
  1658. }
  1659. throw new ParseException (currentLocation, "Invalid instance type.");
  1660. }
  1661. CodeExpression GenerateObjectInstance (object value, bool throwOnError)
  1662. {
  1663. if (value == null)
  1664. return new CodePrimitiveExpression (null);
  1665. if (value is System.Type) {
  1666. CodeTypeReference tref = new CodeTypeReference (value.ToString ());
  1667. return new CodeTypeOfExpression (tref);
  1668. }
  1669. Type t = value.GetType ();
  1670. if (t.IsPrimitive || value is string)
  1671. return new CodePrimitiveExpression (value);
  1672. if (t.IsArray) {
  1673. Array ar = (Array) value;
  1674. CodeExpression[] items = new CodeExpression [ar.Length];
  1675. for (int n=0; n<ar.Length; n++) {
  1676. CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
  1677. if (exp == null) return null;
  1678. items [n] = exp;
  1679. }
  1680. return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
  1681. }
  1682. TypeConverter converter = TypeDescriptor.GetConverter (t);
  1683. if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
  1684. InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
  1685. return GenerateInstance (idesc, throwOnError);
  1686. }
  1687. InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
  1688. if (desc != null) return GenerateInstance (desc, throwOnError);
  1689. if (throwOnError)
  1690. throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
  1691. else
  1692. return null;
  1693. }
  1694. InstanceDescriptor GetDefaultInstanceDescriptor (object value)
  1695. {
  1696. if (value is System.Web.UI.WebControls.Unit) {
  1697. System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
  1698. ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
  1699. BindingFlags.Instance | BindingFlags.Public,
  1700. null,
  1701. new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
  1702. null);
  1703. return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
  1704. }
  1705. if (value is System.Web.UI.WebControls.FontUnit) {
  1706. System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
  1707. Type cParamType = null;
  1708. object cParam = null;
  1709. switch (s.Type) {
  1710. case FontSize.AsUnit:
  1711. case FontSize.NotSet:
  1712. cParamType = typeof (System.Web.UI.WebControls.Unit);
  1713. cParam = s.Unit;
  1714. break;
  1715. default:
  1716. cParamType = typeof (string);
  1717. cParam = s.Type.ToString ();
  1718. break;
  1719. }
  1720. ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
  1721. BindingFlags.Instance | BindingFlags.Public,
  1722. null,
  1723. new Type[] {cParamType},
  1724. null);
  1725. if (c != null)
  1726. return new InstanceDescriptor (c, new object[] {cParam});
  1727. }
  1728. return null;
  1729. }
  1730. #if DEBUG
  1731. CodeMethodInvokeExpression CreateConsoleWriteLineCall (string format, params CodeExpression[] parms)
  1732. {
  1733. CodeMethodReferenceExpression cwl = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (System.Console)), "WriteLine");
  1734. CodeMethodInvokeExpression cwlCall = new CodeMethodInvokeExpression (cwl);
  1735. cwlCall.Parameters.Add (new CodePrimitiveExpression (format));
  1736. if (parms != null && parms.Length > 0)
  1737. foreach (CodeExpression expr in parms)
  1738. cwlCall.Parameters.Add (expr);
  1739. return cwlCall;
  1740. }
  1741. #endif
  1742. }
  1743. }