2 // System.Web.Compilation.TemplateControlCompiler
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections;
33 using System.ComponentModel;
35 using System.Globalization;
36 using System.Reflection;
40 using System.Web.UI.WebControls;
41 using System.Web.Util;
42 using System.ComponentModel.Design.Serialization;
44 using System.Configuration;
45 using System.Collections.Specialized;
46 using System.Collections.Generic;
47 using System.Text.RegularExpressions;
48 using System.Web.Configuration;
51 namespace System.Web.Compilation
53 class TemplateControlCompiler : BaseCompiler
55 static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
56 BindingFlags.Instance | BindingFlags.IgnoreCase;
58 TemplateControlParser parser;
60 ILocation currentLocation;
62 static TypeConverter colorConverter;
64 internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
67 static Regex bindRegex = new Regex (@"Bind\s*\(""(.*?)""\)\s*%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
68 static Regex bindRegexInValue = new Regex (@"Bind\s*\(""(.*?)""\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
71 public TemplateControlCompiler (TemplateControlParser parser)
77 protected void EnsureID (ControlBuilder builder)
79 if (builder.ID == null || builder.ID.Trim () == "")
80 builder.ID = builder.GetNextID (null);
83 void CreateField (ControlBuilder builder, bool check)
85 if (builder == null || builder.ID == null || builder.ControlType == null)
88 if (partialNameOverride [builder.ID] != null)
92 MemberAttributes ma = MemberAttributes.Family;
93 currentLocation = builder.location;
94 if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType, ref ma))
95 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;
101 field.Type.Options |= CodeTypeReferenceOptions.GlobalReference;
103 if (partialClass != null)
104 partialClass.Members.Add (field);
107 mainClass.Members.Add (field);
110 bool CheckBaseFieldOrProperty (string id, Type type, ref MemberAttributes ma)
112 FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);
115 if (fld == null || fld.IsPrivate) {
116 PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
118 MethodInfo setm = prop.GetSetMethod (true);
120 other = prop.PropertyType;
123 other = fld.FieldType;
129 if (!other.IsAssignableFrom (type)) {
131 ma |= MemberAttributes.New;
134 string msg = String.Format ("The base class includes the field '{0}', but its " +
135 "type '{1}' is not compatible with {2}",
137 throw new ParseException (currentLocation, msg);
144 void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr)
146 if (!builder.haveParserVariable) {
147 CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
149 p.Type = new CodeTypeReference (typeof (IParserAccessor));
150 p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
151 builder.methodStatements.Add (p);
152 builder.haveParserVariable = true;
155 CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
156 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
157 invoke.Parameters.Add (expr);
158 builder.methodStatements.Add (invoke);
161 void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
163 string tailname = ((builder is RootBuilder) ? "Tree" : ("_" + builder.ID));
164 CodeMemberMethod method = new CodeMemberMethod ();
165 builder.method = method;
166 builder.methodStatements = method.Statements;
168 method.Name = "__BuildControl" + tailname;
169 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
170 Type type = builder.ControlType;
172 /* in the case this is the __BuildControlTree
173 * method, allow subclasses to insert control
175 if (builder is RootBuilder) {
177 SetCustomAttributes (method);
179 AddStatementsToInitMethod (method);
182 if (builder.HasAspCode) {
183 CodeMemberMethod renderMethod = new CodeMemberMethod ();
184 builder.renderMethod = renderMethod;
185 renderMethod.Name = "__Render" + tailname;
186 renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
187 CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
188 arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
189 arg1.Name = "__output";
190 CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
191 arg2.Type = new CodeTypeReference (typeof (Control));
192 arg2.Name = "parameterContainer";
193 renderMethod.Parameters.Add (arg1);
194 renderMethod.Parameters.Add (arg2);
195 mainClass.Members.Add (renderMethod);
198 if (childrenAsProperties || builder.ControlType == null) {
200 if (builder is RootBuilder)
201 typeString = parser.ClassName;
203 if (builder.ControlType != null && builder.isProperty &&
204 !typeof (ITemplate).IsAssignableFrom (builder.ControlType))
205 typeString = builder.ControlType.FullName;
207 typeString = "System.Web.UI.Control";
210 method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
213 if (typeof (Control).IsAssignableFrom (type))
214 method.ReturnType = new CodeTypeReference (typeof (Control));
216 // _ctrl = new $controlType ($parameters);
218 CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (type);
220 object [] atts = type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true);
221 if (atts != null && atts.Length > 0) {
222 ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
224 newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
225 } else if (builder is DataBindingBuilder) {
226 newExpr.Parameters.Add (new CodePrimitiveExpression (0));
227 newExpr.Parameters.Add (new CodePrimitiveExpression (1));
230 method.Statements.Add (new CodeVariableDeclarationStatement (builder.ControlType, "__ctrl"));
231 CodeAssignStatement assign = new CodeAssignStatement ();
232 assign.Left = ctrlVar;
233 assign.Right = newExpr;
234 method.Statements.Add (assign);
236 // this.$builderID = _ctrl;
238 CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
239 builderID.TargetObject = thisRef;
240 builderID.FieldName = builder.ID;
241 assign = new CodeAssignStatement ();
242 assign.Left = builderID;
243 assign.Right = ctrlVar;
244 method.Statements.Add (assign);
245 if (typeof (UserControl).IsAssignableFrom (type)) {
246 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
247 mref.TargetObject = builderID;
248 mref.MethodName = "InitializeAsUserControl";
249 CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
250 initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
251 method.Statements.Add (initAsControl);
255 if (builder.ParentTemplateBuilder is System.Web.UI.WebControls.ContentBuilderInternal) {
259 pi = type.GetProperty ("TemplateControl");
260 } catch (Exception) {
264 if (pi != null && pi.CanWrite) {
265 // __ctrl.TemplateControl = this;
266 assign = new CodeAssignStatement ();
267 assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
268 assign.Right = thisRef;
269 method.Statements.Add (assign);
273 // _ctrl.SkinID = $value
274 // _ctrl.ApplyStyleSheetSkin (this);
276 // the SkinID assignment needs to come
277 // before the call to
278 // ApplyStyleSheetSkin, for obvious
279 // reasons. We skip SkinID in
280 // CreateAssignStatementsFromAttributes
283 if (builder.attribs != null) {
284 string skinid = builder.attribs ["skinid"] as string;
286 CreateAssignStatementFromAttribute (builder, "skinid");
288 if (typeof (WebControl).IsAssignableFrom (type)) {
289 CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
290 if (typeof (Page).IsAssignableFrom (parser.BaseType))
291 applyStyleSheetSkin.Parameters.Add (thisRef);
293 applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
294 method.Statements.Add (applyStyleSheetSkin);
298 // process ID here. It should be set before any other attributes are
299 // assigned, since the control code may rely on ID being set. We
300 // skip ID in CreateAssignStatementsFromAttributes
301 if (builder.attribs != null) {
302 string ctl_id = builder.attribs ["id"] as string;
303 if (ctl_id != null && ctl_id != String.Empty)
304 CreateAssignStatementFromAttribute (builder, "id");
307 if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
308 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (thisRef, "ContentPlaceHolders");
309 CodeMethodInvokeExpression addPlaceholder = new CodeMethodInvokeExpression (prop, "Add");
310 addPlaceholder.Parameters.Add (ctrlVar);
311 method.Statements.Add (addPlaceholder);
314 CodeConditionStatement condStatement;
316 // Add the __Template_* field
317 CodeMemberField fld = new CodeMemberField (typeof (ITemplate), "__Template_" + builder.ID);
318 fld.Attributes = MemberAttributes.Private;
319 mainClass.Members.Add (fld);
321 CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
322 templateID.TargetObject = thisRef;
323 templateID.FieldName = "__Template_" + builder.ID;
325 // if ((this.ContentTemplates != null)) {
326 // this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
329 CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
330 contentTemplates.TargetObject = thisRef;
331 contentTemplates.FieldName = "ContentTemplates";
333 CodeIndexerExpression indexer = new CodeIndexerExpression ();
334 indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
335 indexer.Indices.Add (new CodePrimitiveExpression (builder.ID));
337 assign = new CodeAssignStatement ();
338 assign.Left = templateID;
339 assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);
341 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
342 CodeBinaryOperatorType.IdentityInequality,
343 new CodePrimitiveExpression (null)),
346 method.Statements.Add (condStatement);
348 // if ((this.__Template_mainContent != null)) {
349 // this.__Template_mainContent.InstantiateIn(__ctrl);
351 // and also set things up such that any additional code ends up in:
356 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
357 methodRef.TargetObject = templateID;
358 methodRef.MethodName = "InstantiateIn";
360 CodeMethodInvokeExpression instantiateInInvoke;
361 instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);
363 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
364 CodeBinaryOperatorType.IdentityInequality,
365 new CodePrimitiveExpression (null)),
366 new CodeExpressionStatement (instantiateInInvoke));
367 method.Statements.Add (condStatement);
369 // this is the bit that causes the following stuff to end up in the else { }
370 builder.methodStatements = condStatement.FalseStatements;
375 mainClass.Members.Add (method);
379 void SetCustomAttribute (CodeMemberMethod method, UnknownAttributeDescriptor uad)
381 CodeAssignStatement assign = new CodeAssignStatement ();
382 assign.Left = new CodePropertyReferenceExpression (
383 new CodeArgumentReferenceExpression("__ctrl"),
385 assign.Right = GetExpressionFromString (uad.Value.GetType (), uad.Value.ToString (), uad.Info);
387 method.Statements.Add (assign);
390 void SetCustomAttributes (CodeMemberMethod method)
392 Type baseType = parser.BaseType;
393 if (baseType == null)
396 List <UnknownAttributeDescriptor> attrs = parser.UnknownMainAttributes;
397 if (attrs == null || attrs.Count == 0)
400 foreach (UnknownAttributeDescriptor uad in attrs)
401 SetCustomAttribute (method, uad);
405 protected virtual void AddStatementsToInitMethod (CodeMemberMethod method)
409 void AddLiteralSubObject (ControlBuilder builder, string str)
411 if (!builder.HasAspCode) {
412 CodeObjectCreateExpression expr;
413 expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
414 AddParsedSubObjectStmt (builder, expr);
416 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
417 methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
418 methodRef.MethodName = "Write";
420 CodeMethodInvokeExpression expr;
421 expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
422 builder.renderMethod.Statements.Add (expr);
426 string TrimDB (string value)
428 string str = value.Trim ();
429 str = str.Substring (3);
430 return str.Substring (0, str.Length - 2);
433 string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
435 value = TrimDB (value);
436 CodeMemberMethod method;
437 string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
439 bool need_if = false;
440 value = value.Trim ();
441 if (StrUtils.StartsWith (value, "Bind", true)) {
442 Match match = bindRegexInValue.Match (value);
444 value = "Eval" + value.Substring (4);
449 method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
451 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
453 // This should be a CodePropertyReferenceExpression for properties... but it works anyway
454 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
457 if (type == typeof (string)) {
458 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
459 CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
460 tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
461 tostring.Parameters.Add (new CodeSnippetExpression (value));
464 CodeSnippetExpression snippet = new CodeSnippetExpression (value);
465 expr = new CodeCastExpression (type, snippet);
468 CodeAssignStatement assign = new CodeAssignStatement (field, expr);
471 CodeExpression page = new CodePropertyReferenceExpression (thisRef, "Page");
472 CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
473 CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
474 CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
475 method.Statements.Add (ccs);
479 method.Statements.Add (assign);
481 mainClass.Members.Add (method);
485 void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
487 CodeMemberMethod method = builder.method;
488 bool isWritable = IsWritablePropertyOrField (member);
489 if (isDataBound && isWritable) {
490 string dbMethodName = DataBoundProperty (builder, type, var_name, att);
491 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
495 else if (isExpression && isWritable) {
496 AddExpressionAssign (method, member, type, var_name, att);
501 CodeAssignStatement assign = new CodeAssignStatement ();
502 assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
503 currentLocation = builder.location;
504 assign.Right = GetExpressionFromString (type, att, member);
506 method.Statements.Add (assign);
509 bool IsDataBound (string value)
511 if (value == null || value == "")
514 string str = value.Trim ();
515 return (StrUtils.StartsWith (str, "<%#") && StrUtils.EndsWith (str, "%>"));
519 bool IsExpression (string value)
521 if (value == null || value == "")
523 string str = value.Trim ();
524 return (StrUtils.StartsWith (str, "<%$") && StrUtils.EndsWith (str, "%>"));
527 void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
529 string str = value.Trim ();
530 str = str.Substring (3).Trim (); // eats "<%#"
531 if (StrUtils.StartsWith (str, "Bind", true)) {
532 Match match = bindRegex.Match (str);
534 string bindingName = match.Groups [1].Value;
536 TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
537 if (templateBuilder == null || templateBuilder.BindingDirection == BindingDirection.OneWay)
538 throw new HttpException ("Bind expression not allowed in this context.");
540 string id = builder.attribs ["ID"] as string;
542 throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
544 templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
551 static bool InvariantCompare (string a, string b)
553 return (0 == String.Compare (a, b, false, CultureInfo.InvariantCulture));
557 static bool InvariantCompareNoCase (string a, string b)
559 return (0 == String.Compare (a, b, true, CultureInfo.InvariantCulture));
562 static MemberInfo GetFieldOrProperty (Type type, string name)
564 MemberInfo member = null;
566 member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
573 member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
579 static bool IsWritablePropertyOrField (MemberInfo member)
581 PropertyInfo pi = member as PropertyInfo;
584 FieldInfo fi = member as FieldInfo;
586 return !fi.IsInitOnly;
587 throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
590 bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
591 string attValue, string prefix)
593 int hyphen = id.IndexOf ('-');
594 bool isPropertyInfo = (member is PropertyInfo);
595 bool isDataBound = IsDataBound (attValue);
597 bool isExpression = !isDataBound && IsExpression (attValue);
599 bool isExpression = false;
602 if (isPropertyInfo) {
603 type = ((PropertyInfo) member).PropertyType;
605 type = ((FieldInfo) member).FieldType;
608 if (InvariantCompareNoCase (member.Name, id)) {
611 RegisterBindingInfo (builder, member.Name, ref attValue);
614 if (!IsWritablePropertyOrField (member))
617 AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
624 string prop_field = id.Replace ("-", ".");
625 string [] parts = prop_field.Split (new char [] {'.'});
626 int length = parts.Length;
628 if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
632 MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
633 if (sub_member == null)
636 string new_prefix = prefix + member.Name + ".";
637 string new_id = id.Substring (hyphen + 1);
638 return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
641 MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
642 if (!(subpf is PropertyInfo))
645 PropertyInfo subprop = (PropertyInfo) subpf;
646 if (subprop.CanWrite == false)
649 bool is_bool = (subprop.PropertyType == typeof (bool));
650 if (!is_bool && attValue == null)
651 return false; // Font-Size -> Font-Size="" as html
653 string val = attValue;
654 if (attValue == null && is_bool)
655 val = "true"; // Font-Bold <=> Font-Bold="true"
657 if (isDataBound) RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
659 AddCodeForPropertyOrField (builder, subprop.PropertyType,
660 prefix + member.Name + "." + subprop.Name,
661 val, subprop, isDataBound, isExpression);
667 void AddExpressionAssign (CodeMemberMethod method, MemberInfo member, Type type, string name, string value)
669 CodeAssignStatement assign = new CodeAssignStatement ();
670 assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
672 // First let's find the correct expression builder
673 value = value.Substring (3, value.Length - 5).Trim ();
674 int colon = value.IndexOf (':');
677 string prefix = value.Substring (0, colon).Trim ();
678 string expr = value.Substring (colon + 1).Trim ();
680 System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration ("");
683 CompilationSection cs = (CompilationSection)config.GetSection ("system.web/compilation");
686 if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
689 System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
692 string builderType = ceb.Type;
696 t = HttpApplication.LoadType (builderType, true);
697 } catch (Exception e) {
698 throw new HttpException (
699 String.Format ("Failed to load expression builder type `{0}'", builderType), e);
702 if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
703 throw new HttpException (
705 "Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder",
708 System.Web.Compilation.ExpressionBuilder eb = null;
710 ExpressionBuilderContext ctx;
713 eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
714 ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
715 parsedData = eb.ParseExpression (expr, type, ctx);
716 } catch (Exception e) {
717 throw new HttpException (
718 String.Format ("Failed to create an instance of type `{0}'", builderType), e);
721 BoundPropertyEntry bpe = CreateBoundPropertyEntry (member as PropertyInfo, prefix, expr);
722 assign.Right = eb.GetCodeExpression (bpe, parsedData, ctx);
724 method.Statements.Add (assign);
727 BoundPropertyEntry CreateBoundPropertyEntry (PropertyInfo pi, string prefix, string expr)
732 BoundPropertyEntry ret = new BoundPropertyEntry ();
733 ret.Expression = expr;
734 ret.ExpressionPrefix = prefix;
735 ret.Generated = false;
737 ret.PropertyInfo = pi;
738 ret.Type = pi.PropertyType;
743 void AssignPropertyFromResources (CodeMemberMethod method, MemberInfo mi, string attvalue)
745 bool isProperty = mi.MemberType == MemberTypes.Property;
746 bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
748 if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
751 string memberName = mi.Name;
752 string resname = String.Concat (attvalue, ".", memberName);
754 // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
755 string inputFile = parser.InputFile;
756 string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
758 if (StrUtils.StartsWith (inputFile, physPath))
759 inputFile = parser.InputFile.Substring (physPath.Length - 1);
763 char dsc = System.IO.Path.DirectorySeparatorChar;
765 inputFile = inputFile.Replace (dsc, '/');
767 object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
771 if (!isProperty && !isField)
772 return; // an "impossible" case
774 Type declaringType = mi.DeclaringType;
775 CodeAssignStatement assign = new CodeAssignStatement ();
777 assign.Left = new CodePropertyReferenceExpression (ctrlVar, memberName);
778 assign.Right = ResourceExpressionBuilder.CreateGetLocalResourceObject (mi, resname);
780 method.Statements.Add (assign);
783 void AssignPropertiesFromResources (CodeMemberMethod method, Type controlType, string attvalue)
785 // Process all public fields and properties of the control. We don't use GetMembers to make the code
787 FieldInfo [] fields = controlType.GetFields (
788 BindingFlags.Instance | BindingFlags.Static |
789 BindingFlags.Public | BindingFlags.FlattenHierarchy);
790 PropertyInfo [] properties = controlType.GetProperties (
791 BindingFlags.Instance | BindingFlags.Static |
792 BindingFlags.Public | BindingFlags.FlattenHierarchy);
794 foreach (FieldInfo fi in fields)
795 AssignPropertyFromResources (method, fi, attvalue);
796 foreach (PropertyInfo pi in properties)
797 AssignPropertyFromResources (method, pi, attvalue);
800 void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
802 if (attvalue == null || attvalue.Length == 0)
805 Type controlType = builder.ControlType;
806 if (controlType == null)
809 AssignPropertiesFromResources (builder.method, controlType, attvalue);
813 void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
815 //"__ctrl.{0} += new {1} (this.{2});"
816 CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
818 CodeDelegateCreateExpression create;
819 create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
821 CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
822 method.Statements.Add (attach);
825 void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
827 EventInfo [] ev_info = null;
828 Type type = builder.ControlType;
830 string attvalue = builder.attribs [id] as string;
831 if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
833 ev_info = type.GetEvents ();
835 string id_as_event = id.Substring (2);
836 foreach (EventInfo ev in ev_info){
837 if (InvariantCompareNoCase (ev.Name, id_as_event)){
838 AddEventAssign (builder.method,
850 if (id.ToLower () == "meta:resourcekey") {
851 AssignPropertiesFromResources (builder, attvalue);
856 int hyphen = id.IndexOf ('-');
859 alt_id = id.Substring (0, hyphen);
861 MemberInfo fop = GetFieldOrProperty (type, alt_id);
863 if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
867 if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
868 throw new ParseException (builder.location, "Unrecognized attribute: " + id);
871 CodeMemberMethod method = builder.method;
872 bool databound = IsDataBound (attvalue);
875 val = attvalue.Substring (3);
876 val = val.Substring (0, val.Length - 2);
877 CreateDBAttributeMethod (builder, id, val);
879 CodeCastExpression cast;
880 CodeMethodReferenceExpression methodExpr;
881 CodeMethodInvokeExpression expr;
883 cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
884 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
885 expr = new CodeMethodInvokeExpression (methodExpr);
886 expr.Parameters.Add (new CodePrimitiveExpression (id));
887 expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
888 method.Statements.Add (expr);
893 protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
896 bool haveMetaKey = false;
898 this.dataBoundAtts = 0;
899 IDictionary atts = builder.attribs;
900 if (atts == null || atts.Count == 0)
903 foreach (string id in atts.Keys) {
904 if (InvariantCompareNoCase (id, "runat"))
906 // ID is assigned in BuildControltree
907 if (InvariantCompareNoCase (id, "id"))
911 /* we skip SkinID here as it's assigned in BuildControlTree */
912 if (InvariantCompareNoCase (id, "skinid"))
914 if (InvariantCompareNoCase (id, "meta:resourcekey")) {
919 CreateAssignStatementFromAttribute (builder, id);
924 CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
928 void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
930 if (code == null || code.Trim () == "")
933 string id = builder.GetNextID (null);
934 string dbMethodName = "__DataBind_" + id;
935 CodeMemberMethod method = builder.method;
936 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
938 method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
939 CodeCastExpression cast;
940 CodeMethodReferenceExpression methodExpr;
941 CodeMethodInvokeExpression expr;
943 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
944 cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
945 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
946 expr = new CodeMethodInvokeExpression (methodExpr);
947 expr.Parameters.Add (new CodePrimitiveExpression (attr));
948 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
949 tostring.Method = new CodeMethodReferenceExpression (
950 new CodeTypeReferenceExpression (typeof (Convert)),
952 tostring.Parameters.Add (new CodeSnippetExpression (code));
953 expr.Parameters.Add (tostring);
954 method.Statements.Add (expr);
955 mainClass.Members.Add (method);
958 void AddRenderControl (ControlBuilder builder)
960 CodeIndexerExpression indexer = new CodeIndexerExpression ();
961 indexer.TargetObject = new CodePropertyReferenceExpression (
962 new CodeArgumentReferenceExpression ("parameterContainer"),
965 indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
967 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
968 invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
969 builder.renderMethod.Statements.Add (invoke);
970 builder.renderIndex++;
973 protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
975 if (parent == null || child == null)
977 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
978 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
980 object [] atts = null;
982 if (child.ControlType != null)
983 child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
984 if (atts != null && atts.Length > 0) {
985 PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
986 CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
987 CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
988 build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
989 build.Parameters.Add (new CodePrimitiveExpression (child.ID));
992 build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
995 build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
997 build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
998 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
999 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
1000 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
1001 build.Parameters.Add (new CodeDelegateCreateExpression (
1002 new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
1003 thisRef, child.method.Name));
1005 parent.methodStatements.Add (build);
1006 if (parent.HasAspCode)
1007 AddRenderControl (parent);
1011 if (child.isProperty || parent.ChildrenAsProperties) {
1012 expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
1013 parent.methodStatements.Add (expr);
1017 parent.methodStatements.Add (expr);
1018 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
1019 if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
1020 AddParsedSubObjectStmt (parent, field);
1022 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
1023 invoke.Parameters.Add (field);
1024 parent.methodStatements.Add (invoke);
1027 if (parent.HasAspCode)
1028 AddRenderControl (parent);
1031 void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
1033 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1035 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1036 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1038 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1039 newCompiled.Parameters.Add (newBuild);
1041 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1042 method.Statements.Add (assign);
1046 void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
1048 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1050 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1051 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1053 CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
1054 new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);
1056 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
1057 newCompiled.Parameters.Add (newBuild);
1058 newCompiled.Parameters.Add (newExtract);
1060 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1061 method.Statements.Add (assign);
1064 string CreateExtractValuesMethod (TemplateBuilder builder)
1066 CodeMemberMethod method = new CodeMemberMethod ();
1067 method.Name = "__ExtractValues_" + builder.ID;
1068 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1069 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);
1077 CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
1078 newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
1079 method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
1080 CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
1082 if (builder.Bindings != null) {
1083 Hashtable hash = new Hashtable ();
1084 foreach (TemplateBinding binding in builder.Bindings) {
1085 CodeConditionStatement sif;
1086 CodeVariableReferenceExpression control;
1087 CodeAssignStatement assign;
1089 if (hash [binding.ControlId] == null) {
1091 CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
1092 method.Statements.Add (dec);
1093 CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
1094 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
1095 invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
1097 assign = new CodeAssignStatement ();
1098 control = new CodeVariableReferenceExpression (binding.ControlId);
1099 assign.Left = control;
1100 assign.Right = new CodeCastExpression (binding.ControlType, invoke);
1101 method.Statements.Add (assign);
1103 sif = new CodeConditionStatement ();
1104 sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
1106 method.Statements.Add (sif);
1108 hash [binding.ControlId] = sif;
1111 sif = (CodeConditionStatement) hash [binding.ControlId];
1112 control = new CodeVariableReferenceExpression (binding.ControlId);
1113 assign = new CodeAssignStatement ();
1114 assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
1115 assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
1116 sif.TrueStatements.Add (assign);
1120 method.Statements.Add (new CodeMethodReturnStatement (tableExp));
1124 void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
1126 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1127 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1129 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1130 newCompiled.Parameters.Add (newBuild);
1132 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
1133 invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
1134 invoke.Parameters.Add (newCompiled);
1136 method.Statements.Add (invoke);
1140 void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
1142 if (cr.Code == null || cr.Code.Trim () == "")
1146 CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
1147 parent.renderMethod.Statements.Add (code);
1151 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
1152 expr.Method = new CodeMethodReferenceExpression (
1153 new CodeArgumentReferenceExpression ("__output"),
1156 expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
1157 parent.renderMethod.Statements.Add (expr);
1160 static Type GetContainerType (ControlBuilder builder)
1162 TemplateBuilder tb = builder as TemplateBuilder;
1163 if (tb != null && tb.ContainerType != null)
1164 return tb.ContainerType;
1166 return builder.BindingContainerType;
1168 Type type = builder.BindingContainerType;
1170 PropertyInfo prop = type.GetProperty ("Items", noCaseFlags & ~BindingFlags.NonPublic);
1174 Type ptype = prop.PropertyType;
1175 if (!typeof (ICollection).IsAssignableFrom (ptype))
1178 prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
1182 return prop.PropertyType;
1186 CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
1188 CodeMemberMethod method = new CodeMemberMethod ();
1189 method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1191 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
1192 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
1194 CodeTypeReference containerRef = new CodeTypeReference (container);
1195 CodeTypeReference targetRef = new CodeTypeReference (target);
1197 CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
1198 decl.Name = "Container";
1199 decl.Type = containerRef;
1200 method.Statements.Add (decl);
1202 decl = new CodeVariableDeclarationStatement();
1203 decl.Name = "target";
1204 decl.Type = targetRef;
1205 method.Statements.Add (decl);
1207 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1208 CodeAssignStatement assign = new CodeAssignStatement ();
1209 assign.Left = targetExpr;
1210 assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
1211 method.Statements.Add (assign);
1213 assign = new CodeAssignStatement ();
1214 assign.Left = new CodeVariableReferenceExpression ("Container");
1215 assign.Right = new CodeCastExpression (containerRef,
1216 new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
1217 method.Statements.Add (assign);
1222 void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
1224 if (db.Code == null || db.Code.Trim () == "")
1228 CreateField (db, false);
1230 string dbMethodName = "__DataBind_" + db.ID;
1231 // Add the method that builds the DataBoundLiteralControl
1232 InitMethod (db, false, false);
1233 CodeMemberMethod method = db.method;
1234 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
1235 method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1237 // Add the DataBind handler
1238 method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
1240 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1241 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1242 invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
1243 invoke.Parameters.Add (new CodePrimitiveExpression (0));
1245 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
1246 tostring.Method = new CodeMethodReferenceExpression (
1247 new CodeTypeReferenceExpression (typeof (Convert)),
1249 tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
1250 invoke.Parameters.Add (tostring);
1251 method.Statements.Add (invoke);
1253 mainClass.Members.Add (method);
1255 AddChildCall (builder, db);
1258 void FlushText (ControlBuilder builder, StringBuilder sb)
1260 if (sb.Length > 0) {
1261 AddLiteralSubObject (builder, sb.ToString ());
1266 protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
1269 bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
1271 if (!isTemplate && !inTemplate) {
1272 CreateField (builder, true);
1273 } else if (!isTemplate) {
1274 bool doCheck = false;
1277 bool singleInstance = false;
1278 ControlBuilder pb = builder.parentBuilder;
1279 TemplateBuilder tpb;
1280 while (pb != null) {
1281 tpb = pb as TemplateBuilder;
1283 pb = pb.parentBuilder;
1287 if (tpb.TemplateInstance == TemplateInstance.Single)
1288 singleInstance = true;
1292 if (!singleInstance)
1294 builder.ID = builder.GetNextID (null);
1299 CreateField (builder, doCheck);
1302 InitMethod (builder, isTemplate, childrenAsProperties);
1303 if (!isTemplate || builder.GetType () == typeof (RootBuilder))
1304 CreateAssignStatementsFromAttributes (builder);
1306 if (builder.Children != null && builder.Children.Count > 0) {
1307 ArrayList templates = null;
1309 StringBuilder sb = new StringBuilder ();
1310 foreach (object b in builder.Children) {
1312 sb.Append ((string) b);
1316 FlushText (builder, sb);
1317 if (b is ObjectTagBuilder) {
1318 ProcessObjectTag ((ObjectTagBuilder) b);
1322 StringPropertyBuilder pb = b as StringPropertyBuilder;
1324 if (pb.Children != null && pb.Children.Count > 0) {
1325 StringBuilder asb = new StringBuilder ();
1326 foreach (string s in pb.Children)
1328 CodeMemberMethod method = builder.method;
1329 CodeAssignStatement assign = new CodeAssignStatement ();
1330 assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
1331 assign.Right = new CodePrimitiveExpression (asb.ToString ());
1332 method.Statements.Add (assign);
1338 if (b is ContentBuilderInternal) {
1339 ContentBuilderInternal cb = (ContentBuilderInternal) b;
1340 CreateControlTree (cb, false, true);
1341 AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
1346 if (b is TemplateBuilder) {
1347 if (templates == null)
1348 templates = new ArrayList ();
1354 if (b is CodeRenderBuilder) {
1355 AddCodeRender (builder, (CodeRenderBuilder) b);
1359 if (b is DataBindingBuilder) {
1360 AddDataBindingLiteral (builder, (DataBindingBuilder) b);
1364 if (b is ControlBuilder) {
1365 ControlBuilder child = (ControlBuilder) b;
1366 CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
1367 AddChildCall (builder, child);
1371 throw new Exception ("???");
1374 FlushText (builder, sb);
1376 if (templates != null) {
1377 foreach (TemplateBuilder b in templates) {
1378 CreateControlTree (b, true, false);
1380 if (b.BindingDirection == BindingDirection.TwoWay) {
1381 string extractMethod = CreateExtractValuesMethod (b);
1382 AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
1386 AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
1392 if (builder.defaultPropertyBuilder != null) {
1393 ControlBuilder b = builder.defaultPropertyBuilder;
1394 CreateControlTree (b, false, true);
1395 AddChildCall (builder, b);
1398 if (builder.HasAspCode) {
1399 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1400 m.TargetObject = thisRef;
1401 m.MethodName = builder.renderMethod.Name;
1403 CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
1404 create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
1405 create.TargetObject = thisRef;
1406 create.MethodName = builder.renderMethod.Name;
1408 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1409 invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
1410 invoke.Parameters.Add (create);
1412 builder.methodStatements.Add (invoke);
1415 if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
1416 builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1419 if (builder is RootBuilder)
1420 if (!String.IsNullOrEmpty (parser.MetaResourceKey))
1421 AssignPropertiesFromResources (builder.method, parser.BaseType, parser.MetaResourceKey);
1425 protected internal override void CreateMethods ()
1427 base.CreateMethods ();
1429 CreateProperties ();
1430 CreateControlTree (parser.RootBuilder, false, false);
1431 CreateFrameworkInitializeMethod ();
1434 void CallBaseFrameworkInitialize (CodeMemberMethod method)
1436 CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
1437 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
1438 method.Statements.Add (invoke);
1441 void CreateFrameworkInitializeMethod ()
1443 CodeMemberMethod method = new CodeMemberMethod ();
1444 method.Name = "FrameworkInitialize";
1445 method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1446 PrependStatementsToFrameworkInitialize (method);
1447 CallBaseFrameworkInitialize (method);
1448 AppendStatementsToFrameworkInitialize (method);
1449 mainClass.Members.Add (method);
1452 protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
1456 protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
1458 if (!parser.EnableViewState) {
1459 CodeAssignStatement stmt = new CodeAssignStatement ();
1460 stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
1461 stmt.Right = new CodePrimitiveExpression (false);
1462 method.Statements.Add (stmt);
1465 CodeMethodReferenceExpression methodExpr;
1466 methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
1467 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
1468 method.Statements.Add (new CodeExpressionStatement (expr));
1471 protected override void AddApplicationAndSessionObjects ()
1473 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
1474 CreateFieldForObject (tag.Type, tag.ObjectID);
1475 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
1478 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
1479 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
1483 protected void ProcessObjectTag (ObjectTagBuilder tag)
1485 string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
1486 CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
1489 void CreateProperties ()
1491 if (!parser.AutoEventWireup) {
1492 CreateAutoEventWireup ();
1494 CreateAutoHandlers ();
1497 CreateApplicationInstance ();
1500 void CreateApplicationInstance ()
1502 CodeMemberProperty prop = new CodeMemberProperty ();
1503 Type appType = typeof (HttpApplication);
1504 prop.Type = new CodeTypeReference (appType);
1505 prop.Name = "ApplicationInstance";
1506 prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
1508 CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
1510 propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
1512 CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
1513 prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
1515 if (partialClass != null)
1516 partialClass.Members.Add (prop);
1519 mainClass.Members.Add (prop);
1522 void CreateAutoHandlers ()
1524 // Create AutoHandlers property
1525 CodeMemberProperty prop = new CodeMemberProperty ();
1526 prop.Type = new CodeTypeReference (typeof (int));
1527 prop.Name = "AutoHandlers";
1528 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1530 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
1531 CodeFieldReferenceExpression fldRef ;
1532 fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
1533 ret.Expression = fldRef;
1534 prop.GetStatements.Add (ret);
1535 prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
1538 CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
1539 prop.CustomAttributes.Add (attr);
1542 mainClass.Members.Add (prop);
1544 // Add the __autoHandlers field
1545 CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
1546 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
1547 mainClass.Members.Add (fld);
1550 void CreateAutoEventWireup ()
1552 // The getter returns false
1553 CodeMemberProperty prop = new CodeMemberProperty ();
1554 prop.Type = new CodeTypeReference (typeof (bool));
1555 prop.Name = "SupportAutoEvents";
1556 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1557 prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
1558 mainClass.Members.Add (prop);
1562 protected virtual string HandleUrlProperty (string str, MemberInfo member)
1568 TypeConverter GetConverterForMember (MemberInfo member)
1570 TypeConverterAttribute tca = null;
1574 attrs = member.GetCustomAttributes (typeof (TypeConverterAttribute), true);
1575 if (attrs.Length > 0)
1576 tca = attrs [0] as TypeConverterAttribute;
1578 attrs = member.GetCustomAttributes (true);
1580 foreach (object attr in attrs) {
1581 tca = attr as TypeConverterAttribute;
1591 string typeName = tca.ConverterTypeName;
1592 if (typeName == null || typeName.Length == 0)
1597 t = HttpApplication.LoadType (typeName);
1598 } catch (Exception) {
1605 return (TypeConverter) Activator.CreateInstance (t);
1608 CodeExpression CreateNullableExpression (Type type, CodeExpression inst, bool nullable)
1614 return new CodeObjectCreateExpression (
1616 new CodeExpression[] {inst}
1623 bool SafeCanConvertFrom (Type type, TypeConverter cvt)
1626 return cvt.CanConvertFrom (type);
1627 } catch (NotImplementedException) {
1632 bool SafeCanConvertTo (Type type, TypeConverter cvt)
1635 return cvt.CanConvertTo (type);
1636 } catch (NotImplementedException) {
1641 CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
1643 TypeConverter cvt = GetConverterForMember (member);
1644 if (cvt != null && !SafeCanConvertFrom (typeof (string), cvt))
1647 object convertedFromAttr = null;
1648 bool preConverted = false;
1649 if (cvt != null && str != null) {
1650 convertedFromAttr = cvt.ConvertFromInvariantString (str);
1651 if (convertedFromAttr != null) {
1652 type = convertedFromAttr.GetType ();
1653 preConverted = true;
1657 bool wasNullable = false;
1658 Type originalType = type;
1660 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
1661 Type[] types = type.GetGenericArguments();
1662 originalType = type;
1663 type = types[0]; // we're interested only in the first type here
1668 if (type == typeof (string)) {
1670 return CreateNullableExpression (originalType,
1671 new CodePrimitiveExpression ((string) convertedFromAttr),
1675 object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
1676 if (urlAttr.Length != 0)
1677 str = HandleUrlProperty (str, member);
1679 return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
1682 if (type == typeof (bool)) {
1684 return CreateNullableExpression (originalType,
1685 new CodePrimitiveExpression ((bool) convertedFromAttr),
1688 if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
1689 return CreateNullableExpression (originalType, new CodePrimitiveExpression (true), wasNullable);
1690 else if (InvariantCompareNoCase (str, "false"))
1691 return CreateNullableExpression (originalType, new CodePrimitiveExpression (false), wasNullable);
1693 else if (wasNullable && InvariantCompareNoCase(str, "null"))
1694 return new CodePrimitiveExpression (null);
1697 throw new ParseException (currentLocation,
1698 "Value '" + str + "' is not a valid boolean.");
1702 return new CodePrimitiveExpression (null);
1704 if (type.IsPrimitive)
1705 return CreateNullableExpression (originalType,
1706 new CodePrimitiveExpression (
1707 Convert.ChangeType (preConverted ? convertedFromAttr : str,
1708 type, CultureInfo.InvariantCulture)),
1711 if (type == typeof (string [])) {
1715 subs = (string[])convertedFromAttr;
1717 subs = str.Split (',');
1718 CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
1719 expr.CreateType = new CodeTypeReference (typeof (string));
1720 foreach (string v in subs)
1721 expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
1723 return CreateNullableExpression (originalType, expr, wasNullable);
1726 if (type == typeof (Color)) {
1729 if (!preConverted) {
1730 if (colorConverter == null)
1731 colorConverter = TypeDescriptor.GetConverter (typeof (Color));
1733 if (str.Trim().Length == 0) {
1734 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
1735 return CreateNullableExpression (originalType,
1736 new CodeFieldReferenceExpression (ft, "Empty"),
1741 if (str.IndexOf (',') == -1) {
1742 c = (Color) colorConverter.ConvertFromString (str);
1744 int [] argb = new int [4];
1747 string [] parts = str.Split (',');
1748 int length = parts.Length;
1750 throw new Exception ();
1752 int basei = (length == 4) ? 0 : 1;
1753 for (int i = length - 1; i >= 0; i--) {
1754 argb [basei + i] = (int) Byte.Parse (parts [i]);
1756 c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
1758 } catch (Exception e) {
1759 // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
1760 // TypeConverter for Color fails to ConvertFromString.
1761 // Hence this hack...
1762 if (InvariantCompareNoCase ("LightGrey", str)) {
1763 c = Color.LightGray;
1765 throw new ParseException (currentLocation,
1766 "Color " + str + " is not a valid color.", e);
1770 c = (Color)convertedFromAttr;
1772 if (c.IsKnownColor) {
1773 CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
1774 if (c.IsSystemColor)
1775 type = typeof (SystemColors);
1777 expr.TargetObject = new CodeTypeReferenceExpression (type);
1778 expr.FieldName = c.Name;
1779 return CreateNullableExpression (originalType, expr, wasNullable);
1781 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1782 m.TargetObject = new CodeTypeReferenceExpression (type);
1783 m.MethodName = "FromArgb";
1784 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1785 invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
1786 invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
1787 invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
1788 invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
1789 return CreateNullableExpression (originalType, invoke, wasNullable);
1793 TypeConverter converter = preConverted ? cvt :
1794 wasNullable ? TypeDescriptor.GetConverter (type) :
1795 TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
1797 if (preConverted || (converter != null && SafeCanConvertFrom (typeof (string), converter))) {
1798 object value = preConverted ? convertedFromAttr : converter.ConvertFromInvariantString (str);
1800 if (SafeCanConvertTo (typeof (InstanceDescriptor), converter)) {
1801 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1803 return CreateNullableExpression (originalType, GenerateInstance (idesc, true),
1806 return new CodeCastExpression (type, GenerateInstance (idesc, true));
1809 CodeExpression exp = GenerateObjectInstance (value, false);
1811 return CreateNullableExpression (originalType, exp, wasNullable);
1813 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1814 m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
1815 m.MethodName = "GetConverter";
1816 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1817 CodeTypeReference tref = new CodeTypeReference (type);
1818 invoke.Parameters.Add (new CodeTypeOfExpression (tref));
1820 invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
1821 invoke.Parameters.Add (new CodePrimitiveExpression (str));
1824 return CreateNullableExpression (originalType, invoke, wasNullable);
1826 return new CodeCastExpression (type, invoke);
1829 Console.WriteLine ("Unknown type: " + type + " value: " + str);
1831 return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
1834 CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
1836 CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
1838 foreach (object ob in idesc.Arguments) {
1839 CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
1840 if (exp == null) return null;
1841 parameters [n++] = exp;
1844 switch (idesc.MemberInfo.MemberType) {
1845 case MemberTypes.Constructor:
1846 CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
1847 return new CodeObjectCreateExpression (tob, parameters);
1849 case MemberTypes.Method:
1850 CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1851 return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
1853 case MemberTypes.Field:
1854 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1855 return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
1857 case MemberTypes.Property:
1858 CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1859 return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
1861 throw new ParseException (currentLocation, "Invalid instance type.");
1864 CodeExpression GenerateObjectInstance (object value, bool throwOnError)
1867 return new CodePrimitiveExpression (null);
1869 if (value is System.Type) {
1870 CodeTypeReference tref = new CodeTypeReference (value.ToString ());
1871 return new CodeTypeOfExpression (tref);
1874 Type t = value.GetType ();
1876 if (t.IsPrimitive || value is string)
1877 return new CodePrimitiveExpression (value);
1880 Array ar = (Array) value;
1881 CodeExpression[] items = new CodeExpression [ar.Length];
1882 for (int n=0; n<ar.Length; n++) {
1883 CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
1884 if (exp == null) return null;
1887 return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
1890 TypeConverter converter = TypeDescriptor.GetConverter (t);
1891 if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
1892 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1893 return GenerateInstance (idesc, throwOnError);
1896 InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
1897 if (desc != null) return GenerateInstance (desc, throwOnError);
1900 throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
1905 InstanceDescriptor GetDefaultInstanceDescriptor (object value)
1907 if (value is System.Web.UI.WebControls.Unit) {
1908 System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
1909 ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
1910 BindingFlags.Instance | BindingFlags.Public,
1912 new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
1915 return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
1918 if (value is System.Web.UI.WebControls.FontUnit) {
1919 System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
1921 Type cParamType = null;
1922 object cParam = null;
1925 case FontSize.AsUnit:
1926 case FontSize.NotSet:
1927 cParamType = typeof (System.Web.UI.WebControls.Unit);
1932 cParamType = typeof (string);
1933 cParam = s.Type.ToString ();
1937 ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
1938 BindingFlags.Instance | BindingFlags.Public,
1940 new Type[] {cParamType},
1943 return new InstanceDescriptor (c, new object[] {cParam});