TemplateControlCompiler.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  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. assign.Right = convert;
  568. method.Statements.Add (assign);
  569. }
  570. void AssignPropertyFromResources (CodeMemberMethod method, MemberInfo mi, string attvalue, string varname)
  571. {
  572. string resname = String.Format ("{0}.{1}", attvalue, mi.Name);
  573. bool isProperty = mi.MemberType == MemberTypes.Property;
  574. bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
  575. if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
  576. return;
  577. Type member_type = null;
  578. if (isProperty) {
  579. PropertyInfo pi = mi as PropertyInfo;
  580. member_type = pi.PropertyType;
  581. } else if (isField) {
  582. FieldInfo fi = mi as FieldInfo;
  583. member_type = fi.FieldType;
  584. } else // should never happen
  585. return;
  586. // __ctrl.Text = System.Convert.ToString(this.GetLocalResourceObject("ButtonResource1.Text"));
  587. object obj = HttpContext.GetLocalResourceObject (HttpContext.Current.Request.FilePath,
  588. resname);
  589. if (obj == null)
  590. return;
  591. CodeAssignStatement assign = new CodeAssignStatement ();
  592. assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
  593. CodeMethodInvokeExpression getlro = new CodeMethodInvokeExpression (
  594. new CodeThisReferenceExpression (),
  595. "GetLocalResourceObject",
  596. new CodeExpression [] { new CodePrimitiveExpression (resname) });
  597. CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
  598. convert.Method = new CodeMethodReferenceExpression (
  599. new CodeTypeReferenceExpression (typeof(System.Convert)),
  600. "ToString");
  601. convert.Parameters.Add (getlro);
  602. assign.Right = convert;
  603. // assign.Left = new CodeVariableReferenceExpression (varname);
  604. // assign.Right = new CodeMethodInvokeExpression (
  605. // new CodeThisReferenceExpression (),
  606. // "GetLocalResourceObject",
  607. // new CodeExpression [] { new CodePrimitiveExpression (resname) });
  608. // method.Statements.Add (assign);
  609. // // if (localResourceObject != null && localResourceObject.GetType() == typeof(member_type))
  610. // CodeConditionStatement ccs = new CodeConditionStatement ();
  611. // CodeBinaryOperatorExpression exp1 = new CodeBinaryOperatorExpression (
  612. // new CodeVariableReferenceExpression (varname),
  613. // CodeBinaryOperatorType.IdentityInequality,
  614. // new CodePrimitiveExpression (null));
  615. // CodeBinaryOperatorExpression exp2 = new CodeBinaryOperatorExpression (
  616. // new CodeMethodInvokeExpression (
  617. // new CodeVariableReferenceExpression (varname),
  618. // "GetType",
  619. // new CodeExpression [] {}),
  620. // CodeBinaryOperatorType.IdentityEquality,
  621. // new CodeTypeOfExpression (
  622. // new CodeTypeReference (member_type.ToString ())));
  623. // ccs.Condition = new CodeBinaryOperatorExpression (
  624. // exp1,
  625. // CodeBinaryOperatorType.BooleanAnd,
  626. // exp2);
  627. // // ctrlVar.Property = (member_type)obj;
  628. // assign = new CodeAssignStatement ();
  629. // assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
  630. // assign.Right = new CodeCastExpression (
  631. // member_type.ToString (),
  632. // new CodeVariableReferenceExpression (varname));
  633. // ccs.TrueStatements.Add (assign);
  634. method.Statements.Add (assign);
  635. }
  636. void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
  637. {
  638. if (attvalue == null || attvalue.Length == 0)
  639. return;
  640. Type controlType = builder.ControlType;
  641. if (controlType == null)
  642. return;
  643. // object obj = null;
  644. // Process all public fields and properties of the control. We don't use GetMembers to make the code
  645. // faster
  646. FieldInfo [] fields = controlType.GetFields (
  647. BindingFlags.Instance | BindingFlags.Static |
  648. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  649. PropertyInfo [] properties = controlType.GetProperties (
  650. BindingFlags.Instance | BindingFlags.Static |
  651. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  652. if (fields.Length > 0 || properties.Length > 0) {
  653. CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement (
  654. typeof (object),
  655. "localResourceObject",
  656. new CodePrimitiveExpression (null));
  657. builder.method.Statements.Add (cvds);
  658. }
  659. foreach (FieldInfo fi in fields)
  660. AssignPropertyFromResources (builder.method, fi, attvalue, "localResourceObject");
  661. foreach (PropertyInfo pi in properties)
  662. AssignPropertyFromResources (builder.method, pi, attvalue, "localResourceObject");
  663. }
  664. #endif
  665. void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
  666. {
  667. //"__ctrl.{0} += new {1} (this.{2});"
  668. CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
  669. CodeDelegateCreateExpression create;
  670. create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
  671. CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
  672. method.Statements.Add (attach);
  673. }
  674. void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
  675. {
  676. EventInfo [] ev_info = null;
  677. Type type = builder.ControlType;
  678. string attvalue = builder.attribs [id] as string;
  679. if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
  680. if (ev_info == null)
  681. ev_info = type.GetEvents ();
  682. string id_as_event = id.Substring (2);
  683. foreach (EventInfo ev in ev_info){
  684. if (InvariantCompareNoCase (ev.Name, id_as_event)){
  685. AddEventAssign (builder.method,
  686. ev.Name,
  687. ev.EventHandlerType,
  688. attvalue);
  689. return;
  690. }
  691. }
  692. }
  693. #if NET_2_0
  694. if (id.ToLower () == "meta:resourcekey") {
  695. AssignPropertiesFromResources (builder, attvalue);
  696. return;
  697. }
  698. #endif
  699. int hyphen = id.IndexOf ('-');
  700. string alt_id = id;
  701. if (hyphen != -1)
  702. alt_id = id.Substring (0, hyphen);
  703. MemberInfo fop = GetFieldOrProperty (type, alt_id);
  704. if (fop != null) {
  705. if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
  706. return;
  707. }
  708. if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
  709. throw new ParseException (builder.location, "Unrecognized attribute: " + id);
  710. string val;
  711. CodeMemberMethod method = builder.method;
  712. bool databound = IsDataBound (attvalue);
  713. if (databound) {
  714. val = attvalue.Substring (3);
  715. val = val.Substring (0, val.Length - 2);
  716. CreateDBAttributeMethod (builder, id, val);
  717. } else {
  718. CodeCastExpression cast;
  719. CodeMethodReferenceExpression methodExpr;
  720. CodeMethodInvokeExpression expr;
  721. cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
  722. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  723. expr = new CodeMethodInvokeExpression (methodExpr);
  724. expr.Parameters.Add (new CodePrimitiveExpression (id));
  725. expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
  726. method.Statements.Add (expr);
  727. }
  728. }
  729. protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
  730. {
  731. this.dataBoundAtts = 0;
  732. IDictionary atts = builder.attribs;
  733. if (atts == null || atts.Count == 0)
  734. return;
  735. foreach (string id in atts.Keys) {
  736. if (InvariantCompareNoCase (id, "runat"))
  737. continue;
  738. #if NET_2_0
  739. /* we skip SkinID here as it's assigned in BuildControlTree */
  740. if (InvariantCompareNoCase (id, "skinid"))
  741. continue;
  742. #endif
  743. CreateAssignStatementFromAttribute (builder, id);
  744. }
  745. }
  746. void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
  747. {
  748. if (code == null || code.Trim () == "")
  749. return;
  750. string id = builder.GetNextID (null);
  751. string dbMethodName = "__DataBind_" + id;
  752. CodeMemberMethod method = builder.method;
  753. AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
  754. method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
  755. CodeCastExpression cast;
  756. CodeMethodReferenceExpression methodExpr;
  757. CodeMethodInvokeExpression expr;
  758. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  759. cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
  760. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  761. expr = new CodeMethodInvokeExpression (methodExpr);
  762. expr.Parameters.Add (new CodePrimitiveExpression (attr));
  763. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  764. tostring.Method = new CodeMethodReferenceExpression (
  765. new CodeTypeReferenceExpression (typeof (Convert)),
  766. "ToString");
  767. tostring.Parameters.Add (new CodeSnippetExpression (code));
  768. expr.Parameters.Add (tostring);
  769. method.Statements.Add (expr);
  770. mainClass.Members.Add (method);
  771. }
  772. void AddRenderControl (ControlBuilder builder)
  773. {
  774. CodeIndexerExpression indexer = new CodeIndexerExpression ();
  775. indexer.TargetObject = new CodePropertyReferenceExpression (
  776. new CodeArgumentReferenceExpression ("parameterContainer"),
  777. "Controls");
  778. indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
  779. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
  780. invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
  781. builder.renderMethod.Statements.Add (invoke);
  782. builder.renderIndex++;
  783. }
  784. protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
  785. {
  786. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
  787. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
  788. object [] atts = child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
  789. if (atts != null && atts.Length > 0) {
  790. PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
  791. CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
  792. CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
  793. build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
  794. build.Parameters.Add (new CodePrimitiveExpression (child.ID));
  795. #if NET_1_1
  796. if (pca.Shared)
  797. build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
  798. else
  799. #endif
  800. build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
  801. build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
  802. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
  803. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
  804. build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
  805. build.Parameters.Add (new CodeDelegateCreateExpression (
  806. new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
  807. thisRef, child.method.Name));
  808. parent.methodStatements.Add (build);
  809. if (parent.HasAspCode)
  810. AddRenderControl (parent);
  811. return;
  812. }
  813. if (child.isProperty || parent.ChildrenAsProperties) {
  814. expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
  815. parent.methodStatements.Add (expr);
  816. return;
  817. }
  818. parent.methodStatements.Add (expr);
  819. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
  820. if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
  821. AddParsedSubObjectStmt (parent, field);
  822. } else {
  823. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
  824. invoke.Parameters.Add (field);
  825. parent.methodStatements.Add (invoke);
  826. }
  827. if (parent.HasAspCode)
  828. AddRenderControl (parent);
  829. }
  830. void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
  831. {
  832. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  833. CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
  834. newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
  835. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  836. newCompiled.Parameters.Add (newBuild);
  837. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  838. method.Statements.Add (assign);
  839. }
  840. #if NET_2_0
  841. void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
  842. {
  843. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  844. CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
  845. newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
  846. CodeObjectCreateExpression newExtract = new CodeObjectCreateExpression (typeof (ExtractTemplateValuesMethod));
  847. newExtract.Parameters.Add (new CodeMethodReferenceExpression (thisRef, extractMethodName));
  848. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
  849. newCompiled.Parameters.Add (newBuild);
  850. newCompiled.Parameters.Add (newExtract);
  851. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  852. method.Statements.Add (assign);
  853. }
  854. string CreateExtractValuesMethod (TemplateBuilder builder)
  855. {
  856. CodeMemberMethod method = new CodeMemberMethod ();
  857. method.Name = "__ExtractValues_" + builder.ID;
  858. method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  859. method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
  860. CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
  861. arg.Type = new CodeTypeReference (typeof (Control));
  862. arg.Name = "__container";
  863. method.Parameters.Add (arg);
  864. mainClass.Members.Add (method);
  865. CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
  866. newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
  867. method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
  868. CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
  869. if (builder.Bindings != null) {
  870. Hashtable hash = new Hashtable ();
  871. foreach (TemplateBinding binding in builder.Bindings) {
  872. CodeConditionStatement sif;
  873. CodeVariableReferenceExpression control;
  874. CodeAssignStatement assign;
  875. if (hash [binding.ControlId] == null) {
  876. CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
  877. method.Statements.Add (dec);
  878. CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
  879. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
  880. invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
  881. assign = new CodeAssignStatement ();
  882. control = new CodeVariableReferenceExpression (binding.ControlId);
  883. assign.Left = control;
  884. assign.Right = new CodeCastExpression (binding.ControlType, invoke);
  885. method.Statements.Add (assign);
  886. sif = new CodeConditionStatement ();
  887. sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
  888. method.Statements.Add (sif);
  889. hash [binding.ControlId] = sif;
  890. }
  891. sif = (CodeConditionStatement) hash [binding.ControlId];
  892. control = new CodeVariableReferenceExpression (binding.ControlId);
  893. assign = new CodeAssignStatement ();
  894. assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
  895. assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
  896. sif.TrueStatements.Add (assign);
  897. }
  898. }
  899. method.Statements.Add (new CodeMethodReturnStatement (tableExp));
  900. return method.Name;
  901. }
  902. void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
  903. {
  904. CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
  905. newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
  906. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  907. newCompiled.Parameters.Add (newBuild);
  908. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
  909. invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
  910. invoke.Parameters.Add (newCompiled);
  911. method.Statements.Add (invoke);
  912. }
  913. #endif
  914. void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
  915. {
  916. if (cr.Code == null || cr.Code.Trim () == "")
  917. return;
  918. if (!cr.IsAssign) {
  919. CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
  920. parent.renderMethod.Statements.Add (code);
  921. return;
  922. }
  923. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
  924. expr.Method = new CodeMethodReferenceExpression (
  925. new CodeArgumentReferenceExpression ("__output"),
  926. "Write");
  927. expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
  928. parent.renderMethod.Statements.Add (expr);
  929. }
  930. static Type GetContainerType (ControlBuilder builder)
  931. {
  932. TemplateBuilder tb = builder as TemplateBuilder;
  933. if (tb != null && tb.ContainerType != null)
  934. return tb.ContainerType;
  935. Type type = builder.BindingContainerType;
  936. PropertyInfo prop = type.GetProperty ("Items", noCaseFlags & ~BindingFlags.NonPublic);
  937. if (prop == null)
  938. return type;
  939. Type ptype = prop.PropertyType;
  940. if (!typeof (ICollection).IsAssignableFrom (ptype))
  941. return type;
  942. prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
  943. if (prop == null)
  944. return type;
  945. return prop.PropertyType;
  946. }
  947. CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
  948. {
  949. CodeMemberMethod method = new CodeMemberMethod ();
  950. method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  951. method.Name = name;
  952. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
  953. method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
  954. CodeTypeReference containerRef = new CodeTypeReference (container);
  955. CodeTypeReference targetRef = new CodeTypeReference (target);
  956. CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
  957. decl.Name = "Container";
  958. decl.Type = containerRef;
  959. method.Statements.Add (decl);
  960. decl = new CodeVariableDeclarationStatement();
  961. decl.Name = "target";
  962. decl.Type = targetRef;
  963. method.Statements.Add (decl);
  964. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  965. CodeAssignStatement assign = new CodeAssignStatement ();
  966. assign.Left = targetExpr;
  967. assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
  968. method.Statements.Add (assign);
  969. assign = new CodeAssignStatement ();
  970. assign.Left = new CodeVariableReferenceExpression ("Container");
  971. assign.Right = new CodeCastExpression (containerRef,
  972. new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
  973. method.Statements.Add (assign);
  974. return method;
  975. }
  976. void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
  977. {
  978. if (db.Code == null || db.Code.Trim () == "")
  979. return;
  980. EnsureID (db);
  981. CreateField (db, false);
  982. string dbMethodName = "__DataBind_" + db.ID;
  983. // Add the method that builds the DataBoundLiteralControl
  984. InitMethod (db, false, false);
  985. CodeMemberMethod method = db.method;
  986. AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
  987. method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  988. // Add the DataBind handler
  989. method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
  990. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  991. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  992. invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
  993. invoke.Parameters.Add (new CodePrimitiveExpression (0));
  994. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  995. tostring.Method = new CodeMethodReferenceExpression (
  996. new CodeTypeReferenceExpression (typeof (Convert)),
  997. "ToString");
  998. tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
  999. invoke.Parameters.Add (tostring);
  1000. method.Statements.Add (invoke);
  1001. mainClass.Members.Add (method);
  1002. AddChildCall (builder, db);
  1003. }
  1004. void FlushText (ControlBuilder builder, StringBuilder sb)
  1005. {
  1006. if (sb.Length > 0) {
  1007. AddLiteralSubObject (builder, sb.ToString ());
  1008. sb.Length = 0;
  1009. }
  1010. }
  1011. protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
  1012. {
  1013. EnsureID (builder);
  1014. bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
  1015. if (!isTemplate && !inTemplate) {
  1016. CreateField (builder, true);
  1017. } else if (!isTemplate) {
  1018. builder.ID = builder.GetNextID (null);
  1019. CreateField (builder, false);
  1020. }
  1021. InitMethod (builder, isTemplate, childrenAsProperties);
  1022. if (!isTemplate || builder.GetType () == typeof (RootBuilder))
  1023. CreateAssignStatementsFromAttributes (builder);
  1024. if (builder.Children != null && builder.Children.Count > 0) {
  1025. ArrayList templates = null;
  1026. StringBuilder sb = new StringBuilder ();
  1027. foreach (object b in builder.Children) {
  1028. if (b is string) {
  1029. sb.Append ((string) b);
  1030. continue;
  1031. }
  1032. FlushText (builder, sb);
  1033. if (b is ObjectTagBuilder) {
  1034. ProcessObjectTag ((ObjectTagBuilder) b);
  1035. continue;
  1036. }
  1037. StringPropertyBuilder pb = b as StringPropertyBuilder;
  1038. if (pb != null){
  1039. if (pb.Children != null && pb.Children.Count > 0) {
  1040. StringBuilder asb = new StringBuilder ();
  1041. foreach (string s in pb.Children)
  1042. asb.Append (s);
  1043. CodeMemberMethod method = builder.method;
  1044. CodeAssignStatement assign = new CodeAssignStatement ();
  1045. assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
  1046. assign.Right = new CodePrimitiveExpression (asb.ToString ());
  1047. method.Statements.Add (assign);
  1048. }
  1049. continue;
  1050. }
  1051. #if NET_2_0
  1052. if (b is ContentBuilderInternal) {
  1053. ContentBuilderInternal cb = (ContentBuilderInternal) b;
  1054. CreateControlTree (cb, false, true);
  1055. AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
  1056. continue;
  1057. }
  1058. #endif
  1059. if (b is TemplateBuilder) {
  1060. if (templates == null)
  1061. templates = new ArrayList ();
  1062. templates.Add (b);
  1063. continue;
  1064. }
  1065. if (b is CodeRenderBuilder) {
  1066. AddCodeRender (builder, (CodeRenderBuilder) b);
  1067. continue;
  1068. }
  1069. if (b is DataBindingBuilder) {
  1070. AddDataBindingLiteral (builder, (DataBindingBuilder) b);
  1071. continue;
  1072. }
  1073. if (b is ControlBuilder) {
  1074. ControlBuilder child = (ControlBuilder) b;
  1075. CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
  1076. AddChildCall (builder, child);
  1077. continue;
  1078. }
  1079. throw new Exception ("???");
  1080. }
  1081. FlushText (builder, sb);
  1082. if (templates != null) {
  1083. foreach (TemplateBuilder b in templates) {
  1084. CreateControlTree (b, true, false);
  1085. #if NET_2_0
  1086. if (b.BindingDirection == BindingDirection.TwoWay) {
  1087. string extractMethod = CreateExtractValuesMethod (b);
  1088. AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
  1089. }
  1090. else
  1091. #endif
  1092. AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
  1093. }
  1094. }
  1095. }
  1096. if (builder.defaultPropertyBuilder != null) {
  1097. ControlBuilder b = builder.defaultPropertyBuilder;
  1098. CreateControlTree (b, false, true);
  1099. AddChildCall (builder, b);
  1100. }
  1101. if (builder.HasAspCode) {
  1102. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1103. m.TargetObject = thisRef;
  1104. m.MethodName = builder.renderMethod.Name;
  1105. CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
  1106. create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
  1107. create.TargetObject = thisRef;
  1108. create.MethodName = builder.renderMethod.Name;
  1109. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
  1110. invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
  1111. invoke.Parameters.Add (create);
  1112. builder.methodStatements.Add (invoke);
  1113. }
  1114. if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
  1115. builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
  1116. }
  1117. protected internal override void CreateMethods ()
  1118. {
  1119. base.CreateMethods ();
  1120. CreateProperties ();
  1121. CreateControlTree (parser.RootBuilder, false, false);
  1122. CreateFrameworkInitializeMethod ();
  1123. }
  1124. void CallBaseFrameworkInitialize (CodeMemberMethod method)
  1125. {
  1126. CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
  1127. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
  1128. method.Statements.Add (invoke);
  1129. }
  1130. void CreateFrameworkInitializeMethod ()
  1131. {
  1132. CodeMemberMethod method = new CodeMemberMethod ();
  1133. method.Name = "FrameworkInitialize";
  1134. method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1135. PrependStatementsToFrameworkInitialize (method);
  1136. CallBaseFrameworkInitialize (method);
  1137. AppendStatementsToFrameworkInitialize (method);
  1138. mainClass.Members.Add (method);
  1139. }
  1140. protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
  1141. {
  1142. }
  1143. protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
  1144. {
  1145. if (!parser.EnableViewState) {
  1146. CodeAssignStatement stmt = new CodeAssignStatement ();
  1147. stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
  1148. stmt.Right = new CodePrimitiveExpression (false);
  1149. method.Statements.Add (stmt);
  1150. }
  1151. CodeMethodReferenceExpression methodExpr;
  1152. methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
  1153. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
  1154. method.Statements.Add (new CodeExpressionStatement (expr));
  1155. }
  1156. protected override void AddApplicationAndSessionObjects ()
  1157. {
  1158. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
  1159. CreateFieldForObject (tag.Type, tag.ObjectID);
  1160. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
  1161. }
  1162. foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
  1163. CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
  1164. }
  1165. }
  1166. protected void ProcessObjectTag (ObjectTagBuilder tag)
  1167. {
  1168. string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
  1169. CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
  1170. }
  1171. void CreateProperties ()
  1172. {
  1173. if (!parser.AutoEventWireup) {
  1174. CreateAutoEventWireup ();
  1175. } else {
  1176. CreateAutoHandlers ();
  1177. }
  1178. CreateApplicationInstance ();
  1179. CreateTemplateSourceDirectory ();
  1180. }
  1181. void CreateTemplateSourceDirectory ()
  1182. {
  1183. CodeMemberProperty prop = new CodeMemberProperty ();
  1184. prop.Type = new CodeTypeReference (typeof (string));
  1185. prop.Name = "TemplateSourceDirectory";
  1186. prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
  1187. CodePrimitiveExpression expr = new CodePrimitiveExpression (parser.BaseVirtualDir);
  1188. prop.GetStatements.Add (new CodeMethodReturnStatement (expr));
  1189. mainClass.Members.Add (prop);
  1190. }
  1191. void CreateApplicationInstance ()
  1192. {
  1193. CodeMemberProperty prop = new CodeMemberProperty ();
  1194. Type appType = typeof (HttpApplication);
  1195. prop.Type = new CodeTypeReference (appType);
  1196. prop.Name = "ApplicationInstance";
  1197. prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
  1198. CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
  1199. propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
  1200. CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
  1201. prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
  1202. mainClass.Members.Add (prop);
  1203. }
  1204. void CreateAutoHandlers ()
  1205. {
  1206. // Create AutoHandlers property
  1207. CodeMemberProperty prop = new CodeMemberProperty ();
  1208. prop.Type = new CodeTypeReference (typeof (int));
  1209. prop.Name = "AutoHandlers";
  1210. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1211. CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
  1212. CodeFieldReferenceExpression fldRef ;
  1213. fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
  1214. ret.Expression = fldRef;
  1215. prop.GetStatements.Add (ret);
  1216. prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
  1217. #if NET_2_0
  1218. CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
  1219. prop.CustomAttributes.Add (attr);
  1220. #endif
  1221. mainClass.Members.Add (prop);
  1222. // Add the __autoHandlers field
  1223. CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
  1224. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  1225. mainClass.Members.Add (fld);
  1226. }
  1227. void CreateAutoEventWireup ()
  1228. {
  1229. // The getter returns false
  1230. CodeMemberProperty prop = new CodeMemberProperty ();
  1231. prop.Type = new CodeTypeReference (typeof (bool));
  1232. prop.Name = "SupportAutoEvents";
  1233. prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
  1234. prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
  1235. mainClass.Members.Add (prop);
  1236. }
  1237. #if NET_2_0
  1238. protected virtual string HandleUrlProperty (string str, MemberInfo member)
  1239. {
  1240. return str;
  1241. }
  1242. #endif
  1243. CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
  1244. {
  1245. #if NET_2_0
  1246. bool wasNullable = false;
  1247. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
  1248. Type[] types = type.GetGenericArguments();
  1249. type = types[0]; // we're interested only in the first type here
  1250. wasNullable = true;
  1251. }
  1252. #endif
  1253. if (type == typeof (string)) {
  1254. #if NET_2_0
  1255. object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
  1256. if (urlAttr.Length != 0)
  1257. str = HandleUrlProperty (str, member);
  1258. #endif
  1259. return new CodePrimitiveExpression (str);
  1260. }
  1261. if (type == typeof (bool)) {
  1262. if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
  1263. return new CodePrimitiveExpression (true);
  1264. else if (InvariantCompareNoCase (str, "false"))
  1265. return new CodePrimitiveExpression (false);
  1266. #if NET_2_0
  1267. else if (wasNullable && InvariantCompareNoCase(str, "null"))
  1268. return new CodePrimitiveExpression (null);
  1269. #endif
  1270. else
  1271. throw new ParseException (currentLocation,
  1272. "Value '" + str + "' is not a valid boolean.");
  1273. }
  1274. if (str == null)
  1275. return new CodePrimitiveExpression (null);
  1276. if (type.IsPrimitive)
  1277. return new CodePrimitiveExpression (Convert.ChangeType (str, type, CultureInfo.InvariantCulture));
  1278. if (type == typeof (string [])) {
  1279. string [] subs = str.Split (',');
  1280. CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
  1281. expr.CreateType = new CodeTypeReference (typeof (string));
  1282. foreach (string v in subs) {
  1283. expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
  1284. }
  1285. return expr;
  1286. }
  1287. if (type == typeof (Color)){
  1288. if (colorConverter == null)
  1289. colorConverter = TypeDescriptor.GetConverter (typeof (Color));
  1290. if (str.Trim().Length == 0) {
  1291. CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
  1292. return new CodeFieldReferenceExpression (ft, "Empty");
  1293. }
  1294. Color c;
  1295. try {
  1296. if (str.IndexOf (',') == -1) {
  1297. c = (Color) colorConverter.ConvertFromString (str);
  1298. } else {
  1299. int [] argb = new int [4];
  1300. argb [0] = 255;
  1301. string [] parts = str.Split (',');
  1302. int length = parts.Length;
  1303. if (length < 3)
  1304. throw new Exception ();
  1305. int basei = (length == 4) ? 0 : 1;
  1306. for (int i = length - 1; i >= 0; i--) {
  1307. argb [basei + i] = (int) Byte.Parse (parts [i]);
  1308. }
  1309. c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
  1310. }
  1311. } catch (Exception e){
  1312. // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
  1313. // TypeConverter for Color fails to ConvertFromString.
  1314. // Hence this hack...
  1315. if (InvariantCompareNoCase ("LightGrey", str)) {
  1316. c = Color.LightGray;
  1317. } else {
  1318. throw new ParseException (currentLocation,
  1319. "Color " + str + " is not a valid color.", e);
  1320. }
  1321. }
  1322. if (c.IsKnownColor){
  1323. CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
  1324. if (c.IsSystemColor)
  1325. type = typeof (SystemColors);
  1326. expr.TargetObject = new CodeTypeReferenceExpression (type);
  1327. expr.FieldName = c.Name;
  1328. return expr;
  1329. } else {
  1330. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1331. m.TargetObject = new CodeTypeReferenceExpression (type);
  1332. m.MethodName = "FromArgb";
  1333. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  1334. invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
  1335. invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
  1336. invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
  1337. invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
  1338. return invoke;
  1339. }
  1340. }
  1341. TypeConverter converter = TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
  1342. if (converter != null && converter.CanConvertFrom (typeof (string))) {
  1343. object value = converter.ConvertFrom (str);
  1344. if (converter.CanConvertTo (typeof (InstanceDescriptor))) {
  1345. InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
  1346. return GenerateInstance (idesc, true);
  1347. }
  1348. CodeExpression exp = GenerateObjectInstance (value, false);
  1349. if (exp != null) return exp;
  1350. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
  1351. m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
  1352. m.MethodName = "GetConverter";
  1353. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
  1354. CodeTypeReference tref = new CodeTypeReference (type);
  1355. invoke.Parameters.Add (new CodeTypeOfExpression (tref));
  1356. invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
  1357. invoke.Parameters.Add (new CodePrimitiveExpression (str));
  1358. return new CodeCastExpression (tref, invoke);
  1359. }
  1360. Console.WriteLine ("Unknown type: " + type + " value: " + str);
  1361. return new CodePrimitiveExpression (str);
  1362. }
  1363. CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
  1364. {
  1365. CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
  1366. int n = 0;
  1367. foreach (object ob in idesc.Arguments) {
  1368. CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
  1369. if (exp == null) return null;
  1370. parameters [n++] = exp;
  1371. }
  1372. switch (idesc.MemberInfo.MemberType) {
  1373. case MemberTypes.Constructor:
  1374. CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
  1375. return new CodeObjectCreateExpression (tob, parameters);
  1376. case MemberTypes.Method:
  1377. CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1378. return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
  1379. case MemberTypes.Field:
  1380. CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1381. return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
  1382. case MemberTypes.Property:
  1383. CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
  1384. return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
  1385. }
  1386. throw new ParseException (currentLocation, "Invalid instance type.");
  1387. }
  1388. CodeExpression GenerateObjectInstance (object value, bool throwOnError)
  1389. {
  1390. if (value == null)
  1391. return new CodePrimitiveExpression (null);
  1392. Type t = value.GetType();
  1393. if (t.IsPrimitive || value is string)
  1394. return new CodePrimitiveExpression (value);
  1395. if (t.IsArray) {
  1396. Array ar = (Array) value;
  1397. CodeExpression[] items = new CodeExpression [ar.Length];
  1398. for (int n=0; n<ar.Length; n++) {
  1399. CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
  1400. if (exp == null) return null;
  1401. items [n] = exp;
  1402. }
  1403. return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
  1404. }
  1405. TypeConverter converter = TypeDescriptor.GetConverter (t);
  1406. if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
  1407. InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
  1408. return GenerateInstance (idesc, throwOnError);
  1409. }
  1410. InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
  1411. if (desc != null) return GenerateInstance (desc, throwOnError);
  1412. if (throwOnError)
  1413. throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
  1414. else
  1415. return null;
  1416. }
  1417. InstanceDescriptor GetDefaultInstanceDescriptor (object value)
  1418. {
  1419. if (value is System.Web.UI.WebControls.Unit) {
  1420. System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
  1421. MethodInfo met = typeof(System.Web.UI.WebControls.Unit).GetMethod ("Parse", new Type[] {typeof(string)});
  1422. return new InstanceDescriptor (met, new object[] {s.ToString ()});
  1423. }
  1424. if (value is System.Web.UI.WebControls.FontUnit) {
  1425. System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
  1426. MethodInfo met = typeof(System.Web.UI.WebControls.FontUnit).GetMethod ("Parse", new Type[] {typeof(string)});
  1427. return new InstanceDescriptor (met, new object[] {s.ToString ()});
  1428. }
  1429. return null;
  1430. }
  1431. }
  1432. }