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