PageRenderTime 60ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/mcs/class/System.Web/System.Web.Compilation/TemplateControlCompiler.cs

https://bitbucket.org/danipen/mono
C# | 2243 lines | 1752 code | 397 blank | 94 comment | 463 complexity | 565d6bbc2f57ccdd5d3ebe75241614c9 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. //
  2. // System.Web.Compilation.TemplateControlCompiler
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier (gonzalo@ximian.com)
  6. // Marek Habersack (mhabersack@novell.com)
  7. //
  8. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  9. // (C) 2004-2008 Novell, Inc (http://novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.CodeDom;
  32. using System.Collections;
  33. using System.ComponentModel;
  34. using System.Configuration;
  35. using System.Collections.Specialized;
  36. using System.Collections.Generic;
  37. using System.Drawing;
  38. using System.Globalization;
  39. using System.Reflection;
  40. using System.Resources;
  41. using System.Text;
  42. using System.Web;
  43. using System.Web.Caching;
  44. using System.Web.Configuration;
  45. using System.Web.UI;
  46. using System.Web.UI.WebControls;
  47. using System.Web.Util;
  48. using System.ComponentModel.Design.Serialization;
  49. using System.Text.RegularExpressions;
  50. namespace System.Web.Compilation
  51. {
  52. class TemplateControlCompiler : BaseCompiler
  53. {
  54. static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
  55. BindingFlags.Instance | BindingFlags.IgnoreCase;
  56. static Type monoTypeType = Type.GetType ("System.MonoType");
  57. TemplateControlParser parser;
  58. int dataBoundAtts;
  59. internal ILocation currentLocation;
  60. static TypeConverter colorConverter;
  61. internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
  62. List <string> masterPageContentPlaceHolders;
  63. static Regex startsWithBindRegex = new Regex (@"^Bind\s*\(", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  64. // When modifying those, make sure to look at the SanitizeBindCall to make sure it
  65. // picks up correct groups.
  66. static Regex bindRegex = new Regex (@"Bind\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)\s*%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  67. static Regex bindRegexInValue = new Regex (@"Bind\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  68. static Regex evalRegexInValue = new Regex (@"(.*)Eval\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)(.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  69. List <string> MasterPageContentPlaceHolders {
  70. get {
  71. if (masterPageContentPlaceHolders == null)
  72. masterPageContentPlaceHolders = new List <string> ();
  73. return masterPageContentPlaceHolders;
  74. }
  75. }
  76. public TemplateControlCompiler (TemplateControlParser parser)
  77. : base (parser)
  78. {
  79. this.parser = parser;
  80. }
  81. protected void EnsureID (ControlBuilder builder)
  82. {
  83. string id = builder.ID;
  84. if (id == null || id.Trim () == String.Empty)
  85. builder.ID = builder.GetNextID (null);
  86. }
  87. void CreateField (ControlBuilder builder, bool check)
  88. {
  89. if (builder == null || builder.ID == null || builder.ControlType == null)
  90. return;
  91. if (partialNameOverride [builder.ID] != null)
  92. return;
  93. MemberAttributes ma = MemberAttributes.Family;
  94. currentLocation = builder.Location;
  95. if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType, ref ma))
  96. return; // The field or property already exists in a base class and is accesible.
  97. CodeMemberField field;
  98. field = new CodeMemberField (builder.ControlType.FullName, builder.ID);
  99. field.Attributes = ma;
  100. field.Type.Options |= CodeTypeReferenceOptions.GlobalReference;
  101. if (partialClass != null)
  102. partialClass.Members.Add (AddLinePragma (field, builder));
  103. else
  104. mainClass.Members.Add (AddLinePragma (field, builder));
  105. }
  106. bool CheckBaseFieldOrProperty (string id, Type type, ref MemberAttributes ma)
  107. {
  108. FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);
  109. Type other = null;
  110. if (fld == null || fld.IsPrivate) {
  111. PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
  112. if (prop != null) {
  113. MethodInfo setm = prop.GetSetMethod (true);
  114. if (setm != null)
  115. other = prop.PropertyType;
  116. }
  117. } else {
  118. other = fld.FieldType;
  119. }
  120. if (other == null)
  121. return false;
  122. if (!other.IsAssignableFrom (type)) {
  123. ma |= MemberAttributes.New;
  124. return false;
  125. }
  126. return true;
  127. }
  128. void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr)
  129. {
  130. if (!builder.HaveParserVariable) {
  131. CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
  132. p.Name = "__parser";
  133. p.Type = new CodeTypeReference (typeof (IParserAccessor));
  134. p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
  135. builder.MethodStatements.Add (p);
  136. builder.HaveParserVariable = true;
  137. }
  138. CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
  139. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
  140. invoke.Parameters.Add (expr);
  141. builder.MethodStatements.Add (AddLinePragma (invoke, builder));
  142. }
  143. CodeStatement CreateControlVariable (Type type, ControlBuilder builder, CodeMemberMethod method, CodeTypeReference ctrlTypeRef)
  144. {
  145. CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (ctrlTypeRef);
  146. object [] atts = type != null ? type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true) : null;
  147. if (atts != null && atts.Length > 0) {
  148. ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
  149. if (att.NeedsTag)
  150. newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
  151. } else if (builder is DataBindingBuilder) {
  152. newExpr.Parameters.Add (new CodePrimitiveExpression (0));
  153. newExpr.Parameters.Add (new CodePrimitiveExpression (1));
  154. }
  155. method.Statements.Add (new CodeVariableDeclarationStatement (ctrlTypeRef, "__ctrl"));
  156. CodeAssignStatement assign = new CodeAssignStatement ();
  157. assign.Left = ctrlVar;
  158. assign.Right = newExpr;
  159. return assign;
  160. }
  161. void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
  162. {
  163. currentLocation = builder.Location;
  164. bool inBuildControlTree = builder is RootBuilder;
  165. string tailname = (inBuildControlTree ? "Tree" : ("_" + builder.ID));
  166. // bool isProperty = builder.IsProperty;
  167. CodeMemberMethod method = new CodeMemberMethod ();
  168. builder.Method = method;
  169. builder.MethodStatements = method.Statements;
  170. method.Name = "__BuildControl" + tailname;
  171. method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  172. Type type = builder.ControlType;
  173. /* in the case this is the __BuildControlTree
  174. * method, allow subclasses to insert control
  175. * specific code. */
  176. if (inBuildControlTree) {
  177. SetCustomAttributes (method);
  178. AddStatementsToInitMethodTop (builder, method);
  179. }
  180. if (builder.HasAspCode) {
  181. CodeMemberMethod renderMethod = new CodeMemberMethod ();
  182. builder.RenderMethod = renderMethod;
  183. renderMethod.Name = "__Render" + tailname;
  184. renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  185. CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
  186. arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
  187. arg1.Name = "__output";
  188. CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
  189. arg2.Type = new CodeTypeReference (typeof (Control));
  190. arg2.Name = "parameterContainer";
  191. renderMethod.Parameters.Add (arg1);
  192. renderMethod.Parameters.Add (arg2);
  193. mainClass.Members.Add (renderMethod);
  194. }
  195. if (childrenAsProperties || type == null) {
  196. string typeString;
  197. bool isGlobal = true;
  198. bool returnsControl;
  199. if (builder is RootBuilder) {
  200. typeString = parser.ClassName;
  201. isGlobal = false;
  202. returnsControl = false;
  203. } else {
  204. returnsControl = builder.PropertyBuilderShouldReturnValue;
  205. if (type != null && builder.IsProperty && !typeof (ITemplate).IsAssignableFrom (type)) {
  206. typeString = type.FullName;
  207. isGlobal = !type.IsPrimitive;
  208. } else
  209. typeString = "System.Web.UI.Control";
  210. ProcessTemplateChildren (builder);
  211. }
  212. CodeTypeReference ctrlTypeRef = new CodeTypeReference (typeString);
  213. if (isGlobal)
  214. ctrlTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
  215. if (returnsControl) {
  216. method.ReturnType = ctrlTypeRef;
  217. // $controlType _ctrl = new $controlType ($parameters);
  218. //
  219. method.Statements.Add (CreateControlVariable (type, builder, method, ctrlTypeRef));
  220. } else
  221. method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
  222. } else {
  223. CodeTypeReference ctrlTypeRef = new CodeTypeReference (type.FullName);
  224. if (!type.IsPrimitive)
  225. ctrlTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
  226. if (typeof (Control).IsAssignableFrom (type))
  227. method.ReturnType = ctrlTypeRef;
  228. // $controlType _ctrl = new $controlType ($parameters);
  229. //
  230. method.Statements.Add (AddLinePragma (CreateControlVariable (type, builder, method, ctrlTypeRef), builder));
  231. // this.$builderID = _ctrl;
  232. //
  233. CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
  234. builderID.TargetObject = thisRef;
  235. builderID.FieldName = builder.ID;
  236. CodeAssignStatement assign = new CodeAssignStatement ();
  237. assign.Left = builderID;
  238. assign.Right = ctrlVar;
  239. method.Statements.Add (AddLinePragma (assign, builder));
  240. if (typeof (UserControl).IsAssignableFrom (type)) {
  241. CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
  242. mref.TargetObject = builderID;
  243. mref.MethodName = "InitializeAsUserControl";
  244. CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
  245. initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
  246. method.Statements.Add (initAsControl);
  247. }
  248. if (builder.ParentTemplateBuilder is System.Web.UI.WebControls.ContentBuilderInternal) {
  249. PropertyInfo pi;
  250. try {
  251. pi = type.GetProperty ("TemplateControl");
  252. } catch (Exception) {
  253. pi = null;
  254. }
  255. if (pi != null && pi.CanWrite) {
  256. // __ctrl.TemplateControl = this;
  257. assign = new CodeAssignStatement ();
  258. assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
  259. assign.Right = thisRef;
  260. method.Statements.Add (assign);
  261. }
  262. }
  263. // _ctrl.SkinID = $value
  264. // _ctrl.ApplyStyleSheetSkin (this);
  265. //
  266. // the SkinID assignment needs to come
  267. // before the call to
  268. // ApplyStyleSheetSkin, for obvious
  269. // reasons. We skip SkinID in
  270. // CreateAssignStatementsFromAttributes
  271. // below.
  272. //
  273. string skinid = builder.GetAttribute ("skinid");
  274. if (!String.IsNullOrEmpty (skinid))
  275. CreateAssignStatementFromAttribute (builder, "skinid");
  276. if (typeof (WebControl).IsAssignableFrom (type)) {
  277. CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
  278. if (typeof (Page).IsAssignableFrom (parser.BaseType))
  279. applyStyleSheetSkin.Parameters.Add (thisRef);
  280. else
  281. applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
  282. method.Statements.Add (applyStyleSheetSkin);
  283. }
  284. // Process template children before anything else
  285. ProcessTemplateChildren (builder);
  286. // process ID here. It should be set before any other attributes are
  287. // assigned, since the control code may rely on ID being set. We
  288. // skip ID in CreateAssignStatementsFromAttributes
  289. string ctl_id = builder.GetAttribute ("id");
  290. if (ctl_id != null && ctl_id.Length != 0)
  291. CreateAssignStatementFromAttribute (builder, "id");
  292. if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
  293. List <string> placeHolderIds = MasterPageContentPlaceHolders;
  294. string cphID = builder.ID;
  295. if (!placeHolderIds.Contains (cphID))
  296. placeHolderIds.Add (cphID);
  297. CodeConditionStatement condStatement;
  298. // Add the __Template_* field
  299. string templateField = "__Template_" + cphID;
  300. CodeMemberField fld = new CodeMemberField (typeof (ITemplate), templateField);
  301. fld.Attributes = MemberAttributes.Private;
  302. mainClass.Members.Add (fld);
  303. CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
  304. templateID.TargetObject = thisRef;
  305. templateID.FieldName = templateField;
  306. CreateContentPlaceHolderTemplateProperty (templateField, "Template_" + cphID);
  307. // if ((this.ContentTemplates != null)) {
  308. // this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
  309. // }
  310. //
  311. CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
  312. contentTemplates.TargetObject = thisRef;
  313. contentTemplates.FieldName = "ContentTemplates";
  314. CodeIndexerExpression indexer = new CodeIndexerExpression ();
  315. indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
  316. indexer.Indices.Add (new CodePrimitiveExpression (cphID));
  317. assign = new CodeAssignStatement ();
  318. assign.Left = templateID;
  319. assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);
  320. condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
  321. CodeBinaryOperatorType.IdentityInequality,
  322. new CodePrimitiveExpression (null)),
  323. assign);
  324. method.Statements.Add (condStatement);
  325. // if ((this.__Template_mainContent != null)) {
  326. // this.__Template_mainContent.InstantiateIn(__ctrl);
  327. // }
  328. // and also set things up such that any additional code ends up in:
  329. // else {
  330. // ...
  331. // }
  332. //
  333. CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
  334. methodRef.TargetObject = templateID;
  335. methodRef.MethodName = "InstantiateIn";
  336. CodeMethodInvokeExpression instantiateInInvoke;
  337. instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);
  338. condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
  339. CodeBinaryOperatorType.IdentityInequality,
  340. new CodePrimitiveExpression (null)),
  341. new CodeExpressionStatement (instantiateInInvoke));
  342. method.Statements.Add (condStatement);
  343. // this is the bit that causes the following stuff to end up in the else { }
  344. builder.MethodStatements = condStatement.FalseStatements;
  345. }
  346. }
  347. if (inBuildControlTree)
  348. AddStatementsToInitMethodBottom (builder, method);
  349. mainClass.Members.Add (method);
  350. }
  351. void ProcessTemplateChildren (ControlBuilder builder)
  352. {
  353. ArrayList templates = builder.TemplateChildren;
  354. if (templates != null && templates.Count > 0) {
  355. foreach (TemplateBuilder tb in templates) {
  356. CreateControlTree (tb, true, false);
  357. if (tb.BindingDirection == BindingDirection.TwoWay) {
  358. string extractMethod = CreateExtractValuesMethod (tb);
  359. AddBindableTemplateInvocation (builder, tb.TagName, tb.Method.Name, extractMethod);
  360. } else
  361. AddTemplateInvocation (builder, tb.TagName, tb.Method.Name);
  362. }
  363. }
  364. }
  365. void SetCustomAttribute (CodeMemberMethod method, UnknownAttributeDescriptor uad)
  366. {
  367. CodeAssignStatement assign = new CodeAssignStatement ();
  368. assign.Left = new CodePropertyReferenceExpression (
  369. new CodeArgumentReferenceExpression("__ctrl"),
  370. uad.Info.Name);
  371. assign.Right = GetExpressionFromString (uad.Value.GetType (), uad.Value.ToString (), uad.Info);
  372. method.Statements.Add (assign);
  373. }
  374. void SetCustomAttributes (CodeMemberMethod method)
  375. {
  376. Type baseType = parser.BaseType;
  377. if (baseType == null)
  378. return;
  379. List <UnknownAttributeDescriptor> attrs = parser.UnknownMainAttributes;
  380. if (attrs == null || attrs.Count == 0)
  381. return;
  382. foreach (UnknownAttributeDescriptor uad in attrs)
  383. SetCustomAttribute (method, uad);
  384. }
  385. protected virtual void AddStatementsToInitMethodTop (ControlBuilder builder, CodeMemberMethod method)
  386. {
  387. #if NET_4_0
  388. ClientIDMode? mode = parser.ClientIDMode;
  389. if (mode.HasValue) {
  390. var cimRef = new CodeTypeReferenceExpression (typeof (ClientIDMode));
  391. cimRef.Type.Options = CodeTypeReferenceOptions.GlobalReference;
  392. var assign = new CodeAssignStatement ();
  393. assign.Left = new CodePropertyReferenceExpression (thisRef, "ClientIDMode");
  394. assign.Right = new CodeFieldReferenceExpression (cimRef, mode.Value.ToString ());
  395. method.Statements.Add (assign);
  396. }
  397. #endif
  398. }
  399. protected virtual void AddStatementsToInitMethodBottom (ControlBuilder builder, CodeMemberMethod method)
  400. {
  401. }
  402. void AddLiteralSubObject (ControlBuilder builder, string str)
  403. {
  404. if (!builder.HasAspCode) {
  405. CodeObjectCreateExpression expr;
  406. expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
  407. AddParsedSubObjectStmt (builder, expr);
  408. } else {
  409. CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
  410. methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
  411. methodRef.MethodName = "Write";
  412. CodeMethodInvokeExpression expr;
  413. expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
  414. builder.RenderMethod.Statements.Add (expr);
  415. }
  416. }
  417. string TrimDB (string value, bool trimTail)
  418. {
  419. string str = value.Trim ();
  420. int len = str.Length;
  421. int idx = str.IndexOf ('#', 2) + 1;
  422. if (idx >= len)
  423. return String.Empty;
  424. if (trimTail)
  425. len -= 2;
  426. return str.Substring (idx, len - idx).Trim ();
  427. }
  428. CodeExpression CreateEvalInvokeExpression (Regex regex, string value, bool isBind)
  429. {
  430. Match match = regex.Match (value);
  431. if (!match.Success) {
  432. if (isBind)
  433. throw new HttpParseException ("Bind invocation wasn't formatted properly.");
  434. return null;
  435. }
  436. string sanitizedSnippet;
  437. if (isBind)
  438. sanitizedSnippet = SanitizeBindCall (match);
  439. else
  440. sanitizedSnippet = value;
  441. return new CodeSnippetExpression (sanitizedSnippet);
  442. }
  443. string SanitizeBindCall (Match match)
  444. {
  445. GroupCollection groups = match.Groups;
  446. StringBuilder sb = new StringBuilder ("Eval(\"" + groups [1] + "\"");
  447. Group second = groups [4];
  448. if (second != null) {
  449. string v = second.Value;
  450. if (v != null && v.Length > 0)
  451. sb.Append (",\"" + second + "\"");
  452. }
  453. sb.Append (")");
  454. return sb.ToString ();
  455. }
  456. string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
  457. {
  458. value = TrimDB (value, true);
  459. CodeMemberMethod method;
  460. string dbMethodName = builder.Method.Name + "_DB_" + dataBoundAtts++;
  461. CodeExpression valueExpression = null;
  462. value = value.Trim ();
  463. bool need_if = false;
  464. if (startsWithBindRegex.Match (value).Success) {
  465. valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, true);
  466. if (valueExpression != null)
  467. need_if = true;
  468. } else
  469. if (StrUtils.StartsWith (value, "Eval", true))
  470. valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, false);
  471. if (valueExpression == null)
  472. valueExpression = new CodeSnippetExpression (value);
  473. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
  474. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  475. // This should be a CodePropertyReferenceExpression for properties... but it works anyway
  476. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
  477. CodeExpression expr;
  478. if (type == typeof (string)) {
  479. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  480. CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
  481. tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
  482. tostring.Parameters.Add (valueExpression);
  483. expr = tostring;
  484. } else
  485. expr = new CodeCastExpression (type, valueExpression);
  486. CodeAssignStatement assign = new CodeAssignStatement (field, expr);
  487. if (need_if) {
  488. CodeExpression page = new CodePropertyReferenceExpression (thisRef, "Page");
  489. CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
  490. CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
  491. CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
  492. method.Statements.Add (ccs);
  493. } else
  494. method.Statements.Add (assign);
  495. mainClass.Members.Add (method);
  496. return method.Name;
  497. }
  498. void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
  499. {
  500. CodeMemberMethod method = builder.Method;
  501. bool isWritable = IsWritablePropertyOrField (member);
  502. if (isDataBound && isWritable) {
  503. string dbMethodName = DataBoundProperty (builder, type, var_name, att);
  504. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  505. return;
  506. } else if (isExpression && isWritable) {
  507. AddExpressionAssign (method, builder, member, type, var_name, att);
  508. return;
  509. }
  510. CodeAssignStatement assign = new CodeAssignStatement ();
  511. assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
  512. currentLocation = builder.Location;
  513. assign.Right = GetExpressionFromString (type, att, member);
  514. method.Statements.Add (AddLinePragma (assign, builder));
  515. }
  516. void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
  517. {
  518. string str = TrimDB (value, false);
  519. if (StrUtils.StartsWith (str, "Bind", true)) {
  520. Match match = bindRegex.Match (str);
  521. if (match.Success) {
  522. string bindingName = match.Groups [1].Value;
  523. TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
  524. if (templateBuilder == null)
  525. throw new HttpException ("Bind expression not allowed in this context.");
  526. if (templateBuilder.BindingDirection == BindingDirection.OneWay)
  527. return;
  528. string id = builder.GetAttribute ("ID");
  529. if (String.IsNullOrEmpty (id))
  530. throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
  531. templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
  532. }
  533. }
  534. }
  535. /*
  536. static bool InvariantCompare (string a, string b)
  537. {
  538. return (0 == String.Compare (a, b, false, Helpers.InvariantCulture));
  539. }
  540. */
  541. static bool InvariantCompareNoCase (string a, string b)
  542. {
  543. return (0 == String.Compare (a, b, true, Helpers.InvariantCulture));
  544. }
  545. internal static MemberInfo GetFieldOrProperty (Type type, string name)
  546. {
  547. MemberInfo member = null;
  548. try {
  549. member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
  550. } catch {}
  551. if (member != null)
  552. return member;
  553. try {
  554. member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
  555. } catch {}
  556. return member;
  557. }
  558. static bool IsWritablePropertyOrField (MemberInfo member)
  559. {
  560. PropertyInfo pi = member as PropertyInfo;
  561. if (pi != null)
  562. return pi.GetSetMethod (false) != null;
  563. FieldInfo fi = member as FieldInfo;
  564. if (fi != null)
  565. return !fi.IsInitOnly;
  566. throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
  567. }
  568. bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
  569. string attValue, string prefix)
  570. {
  571. int hyphen = id.IndexOf ('-');
  572. bool isPropertyInfo = (member is PropertyInfo);
  573. bool isDataBound = BaseParser.IsDataBound (attValue);
  574. bool isExpression = !isDataBound && BaseParser.IsExpression (attValue);
  575. Type type;
  576. if (isPropertyInfo) {
  577. type = ((PropertyInfo) member).PropertyType;
  578. } else {
  579. type = ((FieldInfo) member).FieldType;
  580. }
  581. if (InvariantCompareNoCase (member.Name, id)) {
  582. if (isDataBound)
  583. RegisterBindingInfo (builder, member.Name, ref attValue);
  584. if (!IsWritablePropertyOrField (member))
  585. return false;
  586. AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
  587. return true;
  588. }
  589. if (hyphen == -1)
  590. return false;
  591. string prop_field = id.Replace ('-', '.');
  592. string [] parts = prop_field.Split (new char [] {'.'});
  593. int length = parts.Length;
  594. if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
  595. return false;
  596. if (length > 2) {
  597. MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
  598. if (sub_member == null)
  599. return false;
  600. string new_prefix = prefix + member.Name + ".";
  601. string new_id = id.Substring (hyphen + 1);
  602. return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
  603. }
  604. MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
  605. if (!(subpf is PropertyInfo))
  606. return false;
  607. PropertyInfo subprop = (PropertyInfo) subpf;
  608. if (subprop.CanWrite == false)
  609. return false;
  610. bool is_bool = (subprop.PropertyType == typeof (bool));
  611. if (!is_bool && attValue == null)
  612. return false; // Font-Size -> Font-Size="" as html
  613. string val = attValue;
  614. if (attValue == null && is_bool)
  615. val = "true"; // Font-Bold <=> Font-Bold="true"
  616. if (isDataBound)
  617. RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
  618. AddCodeForPropertyOrField (builder, subprop.PropertyType,
  619. prefix + member.Name + "." + subprop.Name,
  620. val, subprop, isDataBound, isExpression);
  621. return true;
  622. }
  623. internal CodeExpression CompileExpression (MemberInfo member, Type type, string value, bool useSetAttribute)
  624. {
  625. // First let's find the correct expression builder
  626. value = value.Substring (3, value.Length - 5).Trim ();
  627. int colon = value.IndexOf (':');
  628. if (colon == -1)
  629. return null;
  630. string prefix = value.Substring (0, colon).Trim ();
  631. string expr = value.Substring (colon + 1).Trim ();
  632. CompilationSection cs = (CompilationSection)WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
  633. if (cs == null)
  634. return null;
  635. if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
  636. return null;
  637. System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
  638. if (ceb == null)
  639. return null;
  640. string builderType = ceb.Type;
  641. Type t;
  642. try {
  643. t = HttpApplication.LoadType (builderType, true);
  644. } catch (Exception e) {
  645. throw new HttpException (String.Format ("Failed to load expression builder type `{0}'", builderType), e);
  646. }
  647. if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
  648. throw new HttpException (String.Format ("Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder", builderType));
  649. System.Web.Compilation.ExpressionBuilder eb = null;
  650. object parsedData;
  651. ExpressionBuilderContext ctx;
  652. try {
  653. eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
  654. ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
  655. parsedData = eb.ParseExpression (expr, type, ctx);
  656. } catch (Exception e) {
  657. throw new HttpException (String.Format ("Failed to create an instance of type `{0}'", builderType), e);
  658. }
  659. BoundPropertyEntry bpe = CreateBoundPropertyEntry (member as PropertyInfo, prefix, expr, useSetAttribute);
  660. return eb.GetCodeExpression (bpe, parsedData, ctx);
  661. }
  662. void AddExpressionAssign (CodeMemberMethod method, ControlBuilder builder, MemberInfo member, Type type, string name, string value)
  663. {
  664. CodeExpression expr = CompileExpression (member, type, value, false);
  665. if (expr == null)
  666. return;
  667. CodeAssignStatement assign = new CodeAssignStatement ();
  668. assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
  669. TypeCode typeCode = Type.GetTypeCode (type);
  670. if (typeCode != TypeCode.Empty && typeCode != TypeCode.Object && typeCode != TypeCode.DBNull)
  671. assign.Right = CreateConvertToCall (typeCode, expr);
  672. else
  673. assign.Right = new CodeCastExpression (type, expr);
  674. builder.Method.Statements.Add (AddLinePragma (assign, builder));
  675. }
  676. internal static CodeMethodInvokeExpression CreateConvertToCall (TypeCode typeCode, CodeExpression expr)
  677. {
  678. var ret = new CodeMethodInvokeExpression ();
  679. string methodName;
  680. switch (typeCode) {
  681. case TypeCode.Boolean:
  682. methodName = "ToBoolean";
  683. break;
  684. case TypeCode.Char:
  685. methodName = "ToChar";
  686. break;
  687. case TypeCode.SByte:
  688. methodName = "ToSByte";
  689. break;
  690. case TypeCode.Byte:
  691. methodName = "ToByte";
  692. break;
  693. case TypeCode.Int16:
  694. methodName = "ToInt16";
  695. break;
  696. case TypeCode.UInt16:
  697. methodName = "ToUInt16";
  698. break;
  699. case TypeCode.Int32:
  700. methodName = "ToInt32";
  701. break;
  702. case TypeCode.UInt32:
  703. methodName = "ToUInt32";
  704. break;
  705. case TypeCode.Int64:
  706. methodName = "ToInt64";
  707. break;
  708. case TypeCode.UInt64:
  709. methodName = "ToUInt64";
  710. break;
  711. case TypeCode.Single:
  712. methodName = "ToSingle";
  713. break;
  714. case TypeCode.Double:
  715. methodName = "ToDouble";
  716. break;
  717. case TypeCode.Decimal:
  718. methodName = "ToDecimal";
  719. break;
  720. case TypeCode.DateTime:
  721. methodName = "ToDateTime";
  722. break;
  723. case TypeCode.String:
  724. methodName = "ToString";
  725. break;
  726. default:
  727. throw new InvalidOperationException (String.Format ("Unsupported TypeCode '{0}'", typeCode));
  728. }
  729. var typeRef = new CodeTypeReferenceExpression (typeof (Convert));
  730. typeRef.Type.Options = CodeTypeReferenceOptions.GlobalReference;
  731. ret.Method = new CodeMethodReferenceExpression (typeRef, methodName);
  732. ret.Parameters.Add (expr);
  733. ret.Parameters.Add (new CodePropertyReferenceExpression (new CodeTypeReferenceExpression (typeof (System.Globalization.CultureInfo)), "CurrentCulture"));
  734. return ret;
  735. }
  736. BoundPropertyEntry CreateBoundPropertyEntry (PropertyInfo pi, string prefix, string expr, bool useSetAttribute)
  737. {
  738. BoundPropertyEntry ret = new BoundPropertyEntry ();
  739. ret.Expression = expr;
  740. ret.ExpressionPrefix = prefix;
  741. ret.Generated = false;
  742. if (pi != null) {
  743. ret.Name = pi.Name;
  744. ret.PropertyInfo = pi;
  745. ret.Type = pi.PropertyType;
  746. }
  747. ret.UseSetAttribute = useSetAttribute;
  748. return ret;
  749. }
  750. bool ResourceProviderHasObject (string key)
  751. {
  752. IResourceProvider rp = HttpContext.GetResourceProvider (InputVirtualPath.Absolute, true);
  753. if (rp == null)
  754. return false;
  755. IResourceReader rr = rp.ResourceReader;
  756. if (rr == null)
  757. return false;
  758. try {
  759. IDictionaryEnumerator ide = rr.GetEnumerator ();
  760. if (ide == null)
  761. return false;
  762. string dictKey;
  763. while (ide.MoveNext ()) {
  764. dictKey = ide.Key as string;
  765. if (String.IsNullOrEmpty (dictKey))
  766. continue;
  767. if (String.Compare (key, dictKey, StringComparison.Ordinal) == 0)
  768. return true;
  769. }
  770. } finally {
  771. rr.Close ();
  772. }
  773. return false;
  774. }
  775. void AssignPropertyFromResources (ControlBuilder builder, MemberInfo mi, string attvalue)
  776. {
  777. bool isProperty = mi.MemberType == MemberTypes.Property;
  778. bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
  779. if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
  780. return;
  781. object[] attrs = mi.GetCustomAttributes (typeof (LocalizableAttribute), true);
  782. if (attrs != null && attrs.Length > 0 && !((LocalizableAttribute)attrs [0]).IsLocalizable)
  783. return;
  784. string memberName = mi.Name;
  785. string resname = String.Concat (attvalue, ".", memberName);
  786. if (!ResourceProviderHasObject (resname))
  787. return;
  788. // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
  789. string inputFile = parser.InputFile;
  790. string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
  791. if (StrUtils.StartsWith (inputFile, physPath)) {
  792. string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
  793. inputFile = parser.InputFile.Substring (physPath.Length - 1);
  794. if (appVirtualPath != "/")
  795. inputFile = appVirtualPath + inputFile;
  796. } else
  797. return;
  798. char dsc = System.IO.Path.DirectorySeparatorChar;
  799. if (dsc != '/')
  800. inputFile = inputFile.Replace (dsc, '/');
  801. object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
  802. if (obj == null)
  803. return;
  804. if (!isProperty && !isField)
  805. return; // an "impossible" case
  806. CodeAssignStatement assign = new CodeAssignStatement ();
  807. assign.Left = new CodePropertyReferenceExpression (ctrlVar, memberName);
  808. assign.Right = ResourceExpressionBuilder.CreateGetLocalResourceObject (mi, resname);
  809. builder.Method.Statements.Add (AddLinePragma (assign, builder));
  810. }
  811. void AssignPropertiesFromResources (ControlBuilder builder, Type controlType, string attvalue)
  812. {
  813. // Process all public fields and properties of the control. We don't use GetMembers to make the code
  814. // faster
  815. FieldInfo [] fields = controlType.GetFields (
  816. BindingFlags.Instance | BindingFlags.Static |
  817. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  818. PropertyInfo [] properties = controlType.GetProperties (
  819. BindingFlags.Instance | BindingFlags.Static |
  820. BindingFlags.Public | BindingFlags.FlattenHierarchy);
  821. foreach (FieldInfo fi in fields)
  822. AssignPropertyFromResources (builder, fi, attvalue);
  823. foreach (PropertyInfo pi in properties)
  824. AssignPropertyFromResources (builder, pi, attvalue);
  825. }
  826. void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
  827. {
  828. if (attvalue == null || attvalue.Length == 0)
  829. return;
  830. Type controlType = builder.ControlType;
  831. if (controlType == null)
  832. return;
  833. AssignPropertiesFromResources (builder, controlType, attvalue);
  834. }
  835. void AddEventAssign (CodeMemberMethod method, ControlBuilder builder, string name, Type type, string value)
  836. {
  837. //"__ctrl.{0} += new {1} (this.{2});"
  838. CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
  839. CodeDelegateCreateExpression create;
  840. create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
  841. CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
  842. method.Statements.Add (attach);
  843. }
  844. void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
  845. {
  846. EventInfo [] ev_info = null;
  847. Type type = builder.ControlType;
  848. string attvalue = builder.GetAttribute (id);
  849. if (id.Length > 2 && String.Compare (id.Substring (0, 2), "ON", true, Helpers.InvariantCulture) == 0){
  850. if (ev_info == null)
  851. ev_info = type.GetEvents ();
  852. string id_as_event = id.Substring (2);
  853. foreach (EventInfo ev in ev_info){
  854. if (InvariantCompareNoCase (ev.Name, id_as_event)){
  855. AddEventAssign (builder.Method,
  856. builder,
  857. ev.Name,
  858. ev.EventHandlerType,
  859. attvalue);
  860. return;
  861. }
  862. }
  863. }
  864. if (String.Compare (id, "meta:resourcekey", StringComparison.OrdinalIgnoreCase) == 0) {
  865. AssignPropertiesFromResources (builder, attvalue);
  866. return;
  867. }
  868. int hyphen = id.IndexOf ('-');
  869. string alt_id = id;
  870. if (hyphen != -1)
  871. alt_id = id.Substring (0, hyphen);
  872. MemberInfo fop = GetFieldOrProperty (type, alt_id);
  873. if (fop != null) {
  874. if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
  875. return;
  876. }
  877. if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
  878. throw new ParseException (builder.Location, "Unrecognized attribute: " + id);
  879. CodeMemberMethod method = builder.Method;
  880. bool isDatabound = BaseParser.IsDataBound (attvalue);
  881. bool isExpression = !isDatabound && BaseParser.IsExpression (attvalue);
  882. if (isDatabound) {
  883. string value = attvalue.Substring (3, attvalue.Length - 5).Trim ();
  884. CodeExpression valueExpression = null;
  885. if (startsWithBindRegex.Match (value).Success)
  886. valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, true);
  887. else
  888. if (StrUtils.StartsWith (value, "Eval", true))
  889. valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, false);
  890. if (valueExpression == null && value != null && value.Trim () != String.Empty)
  891. valueExpression = new CodeSnippetExpression (value);
  892. CreateDBAttributeMethod (builder, id, valueExpression);
  893. } else {
  894. CodeCastExpression cast;
  895. CodeMethodReferenceExpression methodExpr;
  896. CodeMethodInvokeExpression expr;
  897. cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
  898. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  899. expr = new CodeMethodInvokeExpression (methodExpr);
  900. expr.Parameters.Add (new CodePrimitiveExpression (id));
  901. CodeExpression valueExpr = null;
  902. if (isExpression)
  903. valueExpr = CompileExpression (null, typeof (string), attvalue, true);
  904. if (valueExpr == null)
  905. valueExpr = new CodePrimitiveExpression (attvalue);
  906. expr.Parameters.Add (valueExpr);
  907. method.Statements.Add (AddLinePragma (expr, builder));
  908. }
  909. }
  910. protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
  911. {
  912. this.dataBoundAtts = 0;
  913. IDictionary atts = builder.Attributes;
  914. if (atts == null || atts.Count == 0)
  915. return;
  916. foreach (string id in atts.Keys) {
  917. if (InvariantCompareNoCase (id, "runat"))
  918. continue;
  919. // ID is assigned in BuildControltree
  920. if (InvariantCompareNoCase (id, "id"))
  921. continue;
  922. /* we skip SkinID here as it's assigned in BuildControlTree */
  923. if (InvariantCompareNoCase (id, "skinid"))
  924. continue;
  925. if (InvariantCompareNoCase (id, "meta:resourcekey"))
  926. continue; // ignore, this one's processed at the very end of
  927. // the method
  928. CreateAssignStatementFromAttribute (builder, id);
  929. }
  930. }
  931. void CreateDBAttributeMethod (ControlBuilder builder, string attr, CodeExpression code)
  932. {
  933. if (code == null)
  934. return;
  935. string id = builder.GetNextID (null);
  936. string dbMethodName = "__DataBind_" + id;
  937. CodeMemberMethod method = builder.Method;
  938. AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
  939. method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
  940. builder.DataBindingMethod = method;
  941. CodeCastExpression cast;
  942. CodeMethodReferenceExpression methodExpr;
  943. CodeMethodInvokeExpression expr;
  944. CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
  945. cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
  946. methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
  947. expr = new CodeMethodInvokeExpression (methodExpr);
  948. expr.Parameters.Add (new CodePrimitiveExpression (attr));
  949. CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
  950. tostring.Method = new CodeMethodReferenceExpression (
  951. new CodeTypeReferenceExpression (typeof (Convert)),
  952. "ToString");
  953. tostring.Parameters.Add (code);
  954. expr.Parameters.Add (tostring);
  955. method.Statements.Add (expr);
  956. mainClass.Members.Add (method);
  957. }
  958. void AddRenderControl (ControlBuilder builder)
  959. {
  960. CodeIndexerExpression indexer = new CodeIndexerExpression ();
  961. indexer.TargetObject = new CodePropertyReferenceExpression (
  962. new CodeArgumentReferenceExpression ("parameterContainer"),
  963. "Controls");
  964. indexer.Indices.Add (new CodePrimitiveExpression (builder.RenderIndex));
  965. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
  966. invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
  967. builder.RenderMethod.Statements.Add (invoke);
  968. builder.IncreaseRenderIndex ();
  969. }
  970. protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
  971. {
  972. if (parent == null || child == null)
  973. return;
  974. CodeStatementCollection methodStatements = parent.MethodStatements;
  975. CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.Method.Name);
  976. CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
  977. object [] atts = null;
  978. if (child.ControlType != null)
  979. atts = child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
  980. if (atts != null && atts.Length > 0) {
  981. PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
  982. CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
  983. CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
  984. CodeExpressionCollection parms = build.Parameters;
  985. parms.Add (new CodeArgumentReferenceExpression("__ctrl"));
  986. parms.Add (new CodePrimitiveExpression (child.ID));
  987. if (pca.Shared)
  988. parms.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
  989. else
  990. parms.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
  991. parms.Add (new CodePrimitiveExpression (pca.Duration));
  992. parms.Add (new CodePrimitiveExpression (pca.VaryByParams));
  993. parms.Add (new CodePrimitiveExpression (pca.VaryByControls));
  994. parms.Add (new CodePrimitiveExpression (pca.VaryByCustom));
  995. parms.Add (new CodePrimitiveExpression (pca.SqlDependency));
  996. parms.Add (new CodeDelegateCreateExpression (
  997. new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
  998. thisRef, child.Method.Name));
  999. #if NET_4_0
  1000. string value = pca.ProviderName;
  1001. if (!String.IsNullOrEmpty (value) && String.Compare (OutputCache.DEFAULT_PROVIDER_NAME, value, StringComparison.Ordinal) != 0)
  1002. parms.Add (new CodePrimitiveExpression (value));
  1003. else
  1004. parms.Add (new CodePrimitiveExpression (null));
  1005. #endif
  1006. methodStatements.Add (AddLinePragma (build, parent));
  1007. if (parent.HasAspCode)
  1008. AddRenderControl (parent);
  1009. return;
  1010. }
  1011. if (child.IsProperty || parent.ChildrenAsProperties) {
  1012. if (!child.PropertyBuilderShouldReturnValue) {
  1013. expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
  1014. parent.MethodStatements.Add (AddLinePragma (expr, parent));
  1015. } else {
  1016. string localVarName = parent.GetNextLocalVariableName ("__ctrl");
  1017. methodStatements.Add (new CodeVariableDeclarationStatement (child.Method.ReturnType, localVarName));
  1018. CodeVariableReferenceExpression localVarRef = new CodeVariableReferenceExpression (localVarName);
  1019. CodeAssignStatement assign = new CodeAssignStatement ();
  1020. assign.Left = localVarRef;
  1021. assign.Right = expr;
  1022. methodStatements.Add (AddLinePragma (assign, parent));
  1023. assign = new CodeAssignStatement ();
  1024. assign.Left = new CodeFieldReferenceExpression (ctrlVar, child.TagName);
  1025. assign.Right = localVarRef;
  1026. methodStatements.Add (AddLinePragma (assign, parent));
  1027. }
  1028. return;
  1029. }
  1030. methodStatements.Add (AddLinePragma (expr, parent));
  1031. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
  1032. if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType))
  1033. AddParsedSubObjectStmt (parent, field);
  1034. else {
  1035. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
  1036. invoke.Parameters.Add (field);
  1037. methodStatements.Add (AddLinePragma (invoke, parent));
  1038. }
  1039. if (parent.HasAspCode)
  1040. AddRenderControl (parent);
  1041. }
  1042. void AddTemplateInvocation (ControlBuilder builder, string name, string methodName)
  1043. {
  1044. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  1045. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  1046. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  1047. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  1048. newCompiled.Parameters.Add (newBuild);
  1049. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  1050. builder.Method.Statements.Add (AddLinePragma (assign, builder));
  1051. }
  1052. void AddBindableTemplateInvocation (ControlBuilder builder, string name, string methodName, string extractMethodName)
  1053. {
  1054. CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
  1055. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  1056. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  1057. CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
  1058. new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);
  1059. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
  1060. newCompiled.Parameters.Add (newBuild);
  1061. newCompiled.Parameters.Add (newExtract);
  1062. CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
  1063. builder.Method.Statements.Add (AddLinePragma (assign, builder));
  1064. }
  1065. string CreateExtractValuesMethod (TemplateBuilder builder)
  1066. {
  1067. CodeMemberMethod method = new CodeMemberMethod ();
  1068. method.Name = "__ExtractValues_" + builder.ID;
  1069. method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  1070. method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
  1071. CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
  1072. arg.Type = new CodeTypeReference (typeof (Control));
  1073. arg.Name = "__container";
  1074. method.Parameters.Add (arg);
  1075. mainClass.Members.Add (method);
  1076. CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
  1077. newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
  1078. method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
  1079. CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
  1080. if (builder.Bindings != null) {
  1081. Hashtable hash = new Hashtable ();
  1082. foreach (TemplateBinding binding in builder.Bindings) {
  1083. CodeConditionStatement sif;
  1084. CodeVariableReferenceExpression control;
  1085. CodeAssignStatement assign;
  1086. if (hash [binding.ControlId] == null) {
  1087. CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
  1088. method.Statements.Add (dec);
  1089. CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
  1090. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
  1091. invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
  1092. assign = new CodeAssignStatement ();
  1093. control = new CodeVariableReferenceExpression (binding.ControlId);
  1094. assign.Left = control;
  1095. assign.Right = new CodeCastExpression (binding.ControlType, invoke);
  1096. method.Statements.Add (assign);
  1097. sif = new CodeConditionStatement ();
  1098. sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
  1099. method.Statements.Add (sif);
  1100. hash [binding.ControlId] = sif;
  1101. }
  1102. sif = (CodeConditionStatement) hash [binding.ControlId];
  1103. control = new CodeVariableReferenceExpression (binding.ControlId);
  1104. assign = new CodeAssignStatement ();
  1105. assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
  1106. assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
  1107. sif.TrueStatements.Add (assign);
  1108. }
  1109. }
  1110. method.Statements.Add (new CodeMethodReturnStatement (tableExp));
  1111. return method.Name;
  1112. }
  1113. void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
  1114. {
  1115. CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
  1116. new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
  1117. CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
  1118. newCompiled.Parameters.Add (newBuild);
  1119. CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
  1120. invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
  1121. invoke.Parameters.Add (newCompiled);
  1122. method.Statements.Add (AddLinePragma (invoke, cbuilder));
  1123. }
  1124. void AddCodeRender (ControlBuilder parent, CodeRender

Large files files are truncated, but you can click here to view the full file