TemplateControlCompiler.cs 61 KB

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