2
0

TemplateControlCompiler.cs 66 KB

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