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 internal 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 (AddLinePragma (field, builder));
107 mainClass.Members.Add (AddLinePragma (field, builder));
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 (AddLinePragma (invoke, builder));
161 void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
163 currentLocation = builder.location;
165 string tailname = ((builder is RootBuilder) ? "Tree" : ("_" + builder.ID));
166 CodeMemberMethod method = new CodeMemberMethod ();
167 builder.method = method;
168 builder.methodStatements = method.Statements;
170 method.Name = "__BuildControl" + tailname;
171 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
172 Type type = builder.ControlType;
174 /* in the case this is the __BuildControlTree
175 * method, allow subclasses to insert control
177 if (builder is RootBuilder) {
179 SetCustomAttributes (method);
181 AddStatementsToInitMethod (method);
184 if (builder.HasAspCode) {
185 CodeMemberMethod renderMethod = new CodeMemberMethod ();
186 builder.renderMethod = renderMethod;
187 renderMethod.Name = "__Render" + tailname;
188 renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
189 CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
190 arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
191 arg1.Name = "__output";
192 CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
193 arg2.Type = new CodeTypeReference (typeof (Control));
194 arg2.Name = "parameterContainer";
195 renderMethod.Parameters.Add (arg1);
196 renderMethod.Parameters.Add (arg2);
197 mainClass.Members.Add (renderMethod);
200 if (childrenAsProperties || builder.ControlType == null) {
202 if (builder is RootBuilder)
203 typeString = parser.ClassName;
205 if (builder.ControlType != null && builder.isProperty &&
206 !typeof (ITemplate).IsAssignableFrom (builder.ControlType))
207 typeString = builder.ControlType.FullName;
209 typeString = "System.Web.UI.Control";
212 method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
215 if (typeof (Control).IsAssignableFrom (type))
216 method.ReturnType = new CodeTypeReference (typeof (Control));
218 // _ctrl = new $controlType ($parameters);
220 CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (type);
222 object [] atts = type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true);
223 if (atts != null && atts.Length > 0) {
224 ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
226 newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
227 } else if (builder is DataBindingBuilder) {
228 newExpr.Parameters.Add (new CodePrimitiveExpression (0));
229 newExpr.Parameters.Add (new CodePrimitiveExpression (1));
232 method.Statements.Add (new CodeVariableDeclarationStatement (builder.ControlType, "__ctrl"));
233 CodeAssignStatement assign = new CodeAssignStatement ();
234 assign.Left = ctrlVar;
235 assign.Right = newExpr;
236 method.Statements.Add (AddLinePragma (assign, builder));
238 // this.$builderID = _ctrl;
240 CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
241 builderID.TargetObject = thisRef;
242 builderID.FieldName = builder.ID;
243 assign = new CodeAssignStatement ();
244 assign.Left = builderID;
245 assign.Right = ctrlVar;
246 method.Statements.Add (AddLinePragma (assign, builder));
248 if (typeof (UserControl).IsAssignableFrom (type)) {
249 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
250 mref.TargetObject = builderID;
251 mref.MethodName = "InitializeAsUserControl";
252 CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
253 initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
254 method.Statements.Add (initAsControl);
258 if (builder.ParentTemplateBuilder is System.Web.UI.WebControls.ContentBuilderInternal) {
262 pi = type.GetProperty ("TemplateControl");
263 } catch (Exception) {
267 if (pi != null && pi.CanWrite) {
268 // __ctrl.TemplateControl = this;
269 assign = new CodeAssignStatement ();
270 assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
271 assign.Right = thisRef;
272 method.Statements.Add (assign);
276 // _ctrl.SkinID = $value
277 // _ctrl.ApplyStyleSheetSkin (this);
279 // the SkinID assignment needs to come
280 // before the call to
281 // ApplyStyleSheetSkin, for obvious
282 // reasons. We skip SkinID in
283 // CreateAssignStatementsFromAttributes
286 if (builder.attribs != null) {
287 string skinid = builder.attribs ["skinid"] as string;
289 CreateAssignStatementFromAttribute (builder, "skinid");
291 if (typeof (WebControl).IsAssignableFrom (type)) {
292 CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
293 if (typeof (Page).IsAssignableFrom (parser.BaseType))
294 applyStyleSheetSkin.Parameters.Add (thisRef);
296 applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
297 method.Statements.Add (applyStyleSheetSkin);
301 // process ID here. It should be set before any other attributes are
302 // assigned, since the control code may rely on ID being set. We
303 // skip ID in CreateAssignStatementsFromAttributes
304 if (builder.attribs != null) {
305 string ctl_id = builder.attribs ["id"] as string;
306 if (ctl_id != null && ctl_id != String.Empty)
307 CreateAssignStatementFromAttribute (builder, "id");
310 if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
311 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (thisRef, "ContentPlaceHolders");
312 CodeMethodInvokeExpression addPlaceholder = new CodeMethodInvokeExpression (prop, "Add");
313 addPlaceholder.Parameters.Add (ctrlVar);
314 method.Statements.Add (addPlaceholder);
317 CodeConditionStatement condStatement;
319 // Add the __Template_* field
320 CodeMemberField fld = new CodeMemberField (typeof (ITemplate), "__Template_" + builder.ID);
321 fld.Attributes = MemberAttributes.Private;
322 mainClass.Members.Add (fld);
324 CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
325 templateID.TargetObject = thisRef;
326 templateID.FieldName = "__Template_" + builder.ID;
328 // if ((this.ContentTemplates != null)) {
329 // this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
332 CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
333 contentTemplates.TargetObject = thisRef;
334 contentTemplates.FieldName = "ContentTemplates";
336 CodeIndexerExpression indexer = new CodeIndexerExpression ();
337 indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
338 indexer.Indices.Add (new CodePrimitiveExpression (builder.ID));
340 assign = new CodeAssignStatement ();
341 assign.Left = templateID;
342 assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);
344 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
345 CodeBinaryOperatorType.IdentityInequality,
346 new CodePrimitiveExpression (null)),
349 method.Statements.Add (condStatement);
351 // if ((this.__Template_mainContent != null)) {
352 // this.__Template_mainContent.InstantiateIn(__ctrl);
354 // and also set things up such that any additional code ends up in:
359 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
360 methodRef.TargetObject = templateID;
361 methodRef.MethodName = "InstantiateIn";
363 CodeMethodInvokeExpression instantiateInInvoke;
364 instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);
366 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
367 CodeBinaryOperatorType.IdentityInequality,
368 new CodePrimitiveExpression (null)),
369 new CodeExpressionStatement (instantiateInInvoke));
370 method.Statements.Add (condStatement);
372 // this is the bit that causes the following stuff to end up in the else { }
373 builder.methodStatements = condStatement.FalseStatements;
378 mainClass.Members.Add (method);
382 void SetCustomAttribute (CodeMemberMethod method, UnknownAttributeDescriptor uad)
384 CodeAssignStatement assign = new CodeAssignStatement ();
385 assign.Left = new CodePropertyReferenceExpression (
386 new CodeArgumentReferenceExpression("__ctrl"),
388 assign.Right = GetExpressionFromString (uad.Value.GetType (), uad.Value.ToString (), uad.Info);
390 method.Statements.Add (assign);
393 void SetCustomAttributes (CodeMemberMethod method)
395 Type baseType = parser.BaseType;
396 if (baseType == null)
399 List <UnknownAttributeDescriptor> attrs = parser.UnknownMainAttributes;
400 if (attrs == null || attrs.Count == 0)
403 foreach (UnknownAttributeDescriptor uad in attrs)
404 SetCustomAttribute (method, uad);
408 protected virtual void AddStatementsToInitMethod (CodeMemberMethod method)
412 void AddLiteralSubObject (ControlBuilder builder, string str)
414 if (!builder.HasAspCode) {
415 CodeObjectCreateExpression expr;
416 expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
417 AddParsedSubObjectStmt (builder, expr);
419 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
420 methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
421 methodRef.MethodName = "Write";
423 CodeMethodInvokeExpression expr;
424 expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
425 builder.renderMethod.Statements.Add (AddLinePragma (expr, builder));
429 string TrimDB (string value)
431 string str = value.Trim ();
432 str = str.Substring (3);
433 return str.Substring (0, str.Length - 2);
436 string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
438 value = TrimDB (value);
439 CodeMemberMethod method;
440 string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
442 bool need_if = false;
443 value = value.Trim ();
444 if (StrUtils.StartsWith (value, "Bind", true)) {
445 Match match = bindRegexInValue.Match (value);
447 value = "Eval" + value.Substring (4);
452 method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
454 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
456 // This should be a CodePropertyReferenceExpression for properties... but it works anyway
457 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
460 if (type == typeof (string)) {
461 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
462 CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
463 tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
464 tostring.Parameters.Add (new CodeSnippetExpression (value));
467 CodeSnippetExpression snippet = new CodeSnippetExpression (value);
468 expr = new CodeCastExpression (type, snippet);
471 CodeAssignStatement assign = new CodeAssignStatement (field, expr);
474 CodeExpression page = new CodePropertyReferenceExpression (thisRef, "Page");
475 CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
476 CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
477 CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
478 method.Statements.Add (ccs);
482 method.Statements.Add (assign);
484 mainClass.Members.Add (method);
488 void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
490 CodeMemberMethod method = builder.method;
491 bool isWritable = IsWritablePropertyOrField (member);
492 if (isDataBound && isWritable) {
493 string dbMethodName = DataBoundProperty (builder, type, var_name, att);
494 AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
498 else if (isExpression && isWritable) {
499 AddExpressionAssign (method, builder, member, type, var_name, att);
504 CodeAssignStatement assign = new CodeAssignStatement ();
505 assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
506 currentLocation = builder.location;
507 assign.Right = GetExpressionFromString (type, att, member);
509 method.Statements.Add (AddLinePragma (assign, builder));
512 bool IsDataBound (string value)
514 if (value == null || value == "")
517 string str = value.Trim ();
518 return (StrUtils.StartsWith (str, "<%#") && StrUtils.EndsWith (str, "%>"));
522 bool IsExpression (string value)
524 if (value == null || value == "")
526 string str = value.Trim ();
527 return (StrUtils.StartsWith (str, "<%$") && StrUtils.EndsWith (str, "%>"));
530 void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
532 string str = value.Trim ();
533 str = str.Substring (3).Trim (); // eats "<%#"
534 if (StrUtils.StartsWith (str, "Bind", true)) {
535 Match match = bindRegex.Match (str);
537 string bindingName = match.Groups [1].Value;
539 TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
540 if (templateBuilder == null || templateBuilder.BindingDirection == BindingDirection.OneWay)
541 throw new HttpException ("Bind expression not allowed in this context.");
543 string id = builder.attribs ["ID"] as string;
545 throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
547 templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
554 static bool InvariantCompare (string a, string b)
556 return (0 == String.Compare (a, b, false, CultureInfo.InvariantCulture));
560 static bool InvariantCompareNoCase (string a, string b)
562 return (0 == String.Compare (a, b, true, CultureInfo.InvariantCulture));
565 static MemberInfo GetFieldOrProperty (Type type, string name)
567 MemberInfo member = null;
569 member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
576 member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
582 static bool IsWritablePropertyOrField (MemberInfo member)
584 PropertyInfo pi = member as PropertyInfo;
587 FieldInfo fi = member as FieldInfo;
589 return !fi.IsInitOnly;
590 throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
593 bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
594 string attValue, string prefix)
596 int hyphen = id.IndexOf ('-');
597 bool isPropertyInfo = (member is PropertyInfo);
598 bool isDataBound = IsDataBound (attValue);
600 bool isExpression = !isDataBound && IsExpression (attValue);
602 bool isExpression = false;
605 if (isPropertyInfo) {
606 type = ((PropertyInfo) member).PropertyType;
608 type = ((FieldInfo) member).FieldType;
611 if (InvariantCompareNoCase (member.Name, id)) {
614 RegisterBindingInfo (builder, member.Name, ref attValue);
617 if (!IsWritablePropertyOrField (member))
620 AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
627 string prop_field = id.Replace ("-", ".");
628 string [] parts = prop_field.Split (new char [] {'.'});
629 int length = parts.Length;
631 if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
635 MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
636 if (sub_member == null)
639 string new_prefix = prefix + member.Name + ".";
640 string new_id = id.Substring (hyphen + 1);
641 return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
644 MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
645 if (!(subpf is PropertyInfo))
648 PropertyInfo subprop = (PropertyInfo) subpf;
649 if (subprop.CanWrite == false)
652 bool is_bool = (subprop.PropertyType == typeof (bool));
653 if (!is_bool && attValue == null)
654 return false; // Font-Size -> Font-Size="" as html
656 string val = attValue;
657 if (attValue == null && is_bool)
658 val = "true"; // Font-Bold <=> Font-Bold="true"
660 if (isDataBound) RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
662 AddCodeForPropertyOrField (builder, subprop.PropertyType,
663 prefix + member.Name + "." + subprop.Name,
664 val, subprop, isDataBound, isExpression);
670 void AddExpressionAssign (CodeMemberMethod method, ControlBuilder builder, MemberInfo member, Type type, string name, string value)
672 CodeAssignStatement assign = new CodeAssignStatement ();
673 assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
675 // First let's find the correct expression builder
676 value = value.Substring (3, value.Length - 5).Trim ();
677 int colon = value.IndexOf (':');
680 string prefix = value.Substring (0, colon).Trim ();
681 string expr = value.Substring (colon + 1).Trim ();
683 System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration ("");
686 CompilationSection cs = (CompilationSection)config.GetSection ("system.web/compilation");
689 if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
692 System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
695 string builderType = ceb.Type;
699 t = HttpApplication.LoadType (builderType, true);
700 } catch (Exception e) {
701 throw new HttpException (
702 String.Format ("Failed to load expression builder type `{0}'", builderType), e);
705 if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
706 throw new HttpException (
708 "Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder",
711 System.Web.Compilation.ExpressionBuilder eb = null;
713 ExpressionBuilderContext ctx;
716 eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
717 ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
718 parsedData = eb.ParseExpression (expr, type, ctx);
719 } catch (Exception e) {
720 throw new HttpException (
721 String.Format ("Failed to create an instance of type `{0}'", builderType), e);
724 BoundPropertyEntry bpe = CreateBoundPropertyEntry (member as PropertyInfo, prefix, expr);
725 assign.Right = eb.GetCodeExpression (bpe, parsedData, ctx);
727 builder.method.Statements.Add (AddLinePragma (assign, builder));
730 BoundPropertyEntry CreateBoundPropertyEntry (PropertyInfo pi, string prefix, string expr)
735 BoundPropertyEntry ret = new BoundPropertyEntry ();
736 ret.Expression = expr;
737 ret.ExpressionPrefix = prefix;
738 ret.Generated = false;
740 ret.PropertyInfo = pi;
741 ret.Type = pi.PropertyType;
746 void AssignPropertyFromResources (ControlBuilder builder, MemberInfo mi, string attvalue)
748 bool isProperty = mi.MemberType == MemberTypes.Property;
749 bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
751 if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
754 string memberName = mi.Name;
755 string resname = String.Concat (attvalue, ".", memberName);
757 // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
758 string inputFile = parser.InputFile;
759 string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
761 if (StrUtils.StartsWith (inputFile, physPath))
762 inputFile = parser.InputFile.Substring (physPath.Length - 1);
766 char dsc = System.IO.Path.DirectorySeparatorChar;
768 inputFile = inputFile.Replace (dsc, '/');
770 object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
774 if (!isProperty && !isField)
775 return; // an "impossible" case
777 Type declaringType = mi.DeclaringType;
778 CodeAssignStatement assign = new CodeAssignStatement ();
780 assign.Left = new CodePropertyReferenceExpression (ctrlVar, memberName);
781 assign.Right = ResourceExpressionBuilder.CreateGetLocalResourceObject (mi, resname);
783 builder.method.Statements.Add (AddLinePragma (assign, builder));
786 void AssignPropertiesFromResources (ControlBuilder builder, Type controlType, string attvalue)
788 // Process all public fields and properties of the control. We don't use GetMembers to make the code
790 FieldInfo [] fields = controlType.GetFields (
791 BindingFlags.Instance | BindingFlags.Static |
792 BindingFlags.Public | BindingFlags.FlattenHierarchy);
793 PropertyInfo [] properties = controlType.GetProperties (
794 BindingFlags.Instance | BindingFlags.Static |
795 BindingFlags.Public | BindingFlags.FlattenHierarchy);
797 foreach (FieldInfo fi in fields)
798 AssignPropertyFromResources (builder, fi, attvalue);
799 foreach (PropertyInfo pi in properties)
800 AssignPropertyFromResources (builder, pi, attvalue);
803 void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
805 if (attvalue == null || attvalue.Length == 0)
808 Type controlType = builder.ControlType;
809 if (controlType == null)
812 AssignPropertiesFromResources (builder, controlType, attvalue);
816 void AddEventAssign (CodeMemberMethod method, ControlBuilder builder, string name, Type type, string value)
818 //"__ctrl.{0} += new {1} (this.{2});"
819 CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
821 CodeDelegateCreateExpression create;
822 create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
824 CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
825 method.Statements.Add (attach);
828 void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
830 EventInfo [] ev_info = null;
831 Type type = builder.ControlType;
833 string attvalue = builder.attribs [id] as string;
834 if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
836 ev_info = type.GetEvents ();
838 string id_as_event = id.Substring (2);
839 foreach (EventInfo ev in ev_info){
840 if (InvariantCompareNoCase (ev.Name, id_as_event)){
841 AddEventAssign (builder.method,
854 if (id.ToLower () == "meta:resourcekey") {
855 AssignPropertiesFromResources (builder, attvalue);
860 int hyphen = id.IndexOf ('-');
863 alt_id = id.Substring (0, hyphen);
865 MemberInfo fop = GetFieldOrProperty (type, alt_id);
867 if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
871 if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
872 throw new ParseException (builder.location, "Unrecognized attribute: " + id);
875 CodeMemberMethod method = builder.method;
876 bool databound = IsDataBound (attvalue);
879 val = attvalue.Substring (3);
880 val = val.Substring (0, val.Length - 2);
881 CreateDBAttributeMethod (builder, id, val);
883 CodeCastExpression cast;
884 CodeMethodReferenceExpression methodExpr;
885 CodeMethodInvokeExpression expr;
887 cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
888 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
889 expr = new CodeMethodInvokeExpression (methodExpr);
890 expr.Parameters.Add (new CodePrimitiveExpression (id));
891 expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
892 method.Statements.Add (AddLinePragma (expr, builder));
897 protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
899 this.dataBoundAtts = 0;
900 IDictionary atts = builder.attribs;
901 if (atts == null || atts.Count == 0)
904 foreach (string id in atts.Keys) {
905 if (InvariantCompareNoCase (id, "runat"))
907 // ID is assigned in BuildControltree
908 if (InvariantCompareNoCase (id, "id"))
912 /* we skip SkinID here as it's assigned in BuildControlTree */
913 if (InvariantCompareNoCase (id, "skinid"))
915 if (InvariantCompareNoCase (id, "meta:resourcekey"))
916 continue; // ignore, this one's processed at the very end of
919 CreateAssignStatementFromAttribute (builder, id);
923 void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
925 if (code == null || code.Trim () == "")
928 string id = builder.GetNextID (null);
929 string dbMethodName = "__DataBind_" + id;
930 CodeMemberMethod method = builder.method;
931 AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
933 method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
934 CodeCastExpression cast;
935 CodeMethodReferenceExpression methodExpr;
936 CodeMethodInvokeExpression expr;
938 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
939 cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
940 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
941 expr = new CodeMethodInvokeExpression (methodExpr);
942 expr.Parameters.Add (new CodePrimitiveExpression (attr));
943 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
944 tostring.Method = new CodeMethodReferenceExpression (
945 new CodeTypeReferenceExpression (typeof (Convert)),
947 tostring.Parameters.Add (new CodeSnippetExpression (code));
948 expr.Parameters.Add (tostring);
949 method.Statements.Add (expr);
950 mainClass.Members.Add (method);
953 void AddRenderControl (ControlBuilder builder)
955 CodeIndexerExpression indexer = new CodeIndexerExpression ();
956 indexer.TargetObject = new CodePropertyReferenceExpression (
957 new CodeArgumentReferenceExpression ("parameterContainer"),
960 indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
962 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
963 invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
964 builder.renderMethod.Statements.Add (invoke);
965 builder.renderIndex++;
968 protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
970 if (parent == null || child == null)
973 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
974 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
976 object [] atts = null;
978 if (child.ControlType != null)
979 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 build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
985 build.Parameters.Add (new CodePrimitiveExpression (child.ID));
988 build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
991 build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
993 build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
994 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
995 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
996 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
997 build.Parameters.Add (new CodeDelegateCreateExpression (
998 new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
999 thisRef, child.method.Name));
1001 parent.methodStatements.Add (AddLinePragma (build, parent));
1002 if (parent.HasAspCode)
1003 AddRenderControl (parent);
1007 if (child.isProperty || parent.ChildrenAsProperties) {
1008 expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
1009 parent.methodStatements.Add (AddLinePragma (expr, parent));
1013 parent.methodStatements.Add (AddLinePragma (expr, parent));
1014 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
1015 if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType))
1016 AddParsedSubObjectStmt (parent, field);
1018 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
1019 invoke.Parameters.Add (field);
1020 parent.methodStatements.Add (AddLinePragma (invoke, parent));
1023 if (parent.HasAspCode)
1024 AddRenderControl (parent);
1027 void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
1029 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1031 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1032 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1034 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1035 newCompiled.Parameters.Add (newBuild);
1037 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1038 method.Statements.Add (assign);
1042 void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
1044 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1046 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1047 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1049 CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
1050 new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);
1052 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
1053 newCompiled.Parameters.Add (newBuild);
1054 newCompiled.Parameters.Add (newExtract);
1056 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1057 method.Statements.Add (assign);
1060 string CreateExtractValuesMethod (TemplateBuilder builder)
1062 CodeMemberMethod method = new CodeMemberMethod ();
1063 method.Name = "__ExtractValues_" + builder.ID;
1064 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1065 method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
1067 CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
1068 arg.Type = new CodeTypeReference (typeof (Control));
1069 arg.Name = "__container";
1070 method.Parameters.Add (arg);
1071 mainClass.Members.Add (method);
1073 CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
1074 newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
1075 method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
1076 CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
1078 if (builder.Bindings != null) {
1079 Hashtable hash = new Hashtable ();
1080 foreach (TemplateBinding binding in builder.Bindings) {
1081 CodeConditionStatement sif;
1082 CodeVariableReferenceExpression control;
1083 CodeAssignStatement assign;
1085 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));
1093 assign = new CodeAssignStatement ();
1094 control = new CodeVariableReferenceExpression (binding.ControlId);
1095 assign.Left = control;
1096 assign.Right = new CodeCastExpression (binding.ControlType, invoke);
1097 method.Statements.Add (assign);
1099 sif = new CodeConditionStatement ();
1100 sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
1102 method.Statements.Add (sif);
1104 hash [binding.ControlId] = sif;
1107 sif = (CodeConditionStatement) hash [binding.ControlId];
1108 control = new CodeVariableReferenceExpression (binding.ControlId);
1109 assign = new CodeAssignStatement ();
1110 assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
1111 assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
1112 sif.TrueStatements.Add (assign);
1116 method.Statements.Add (new CodeMethodReturnStatement (tableExp));
1120 void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
1122 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1123 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1125 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1126 newCompiled.Parameters.Add (newBuild);
1128 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
1129 invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
1130 invoke.Parameters.Add (newCompiled);
1132 method.Statements.Add (AddLinePragma (invoke, cbuilder));
1136 void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
1138 if (cr.Code == null || cr.Code.Trim () == "")
1142 CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
1143 parent.renderMethod.Statements.Add (AddLinePragma (code, cr));
1147 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
1148 expr.Method = new CodeMethodReferenceExpression (
1149 new CodeArgumentReferenceExpression ("__output"),
1152 expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
1153 parent.renderMethod.Statements.Add (AddLinePragma (expr, cr));
1156 static PropertyInfo GetContainerProperty (Type type, string[] propNames)
1160 foreach (string name in propNames) {
1161 prop = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
1169 static string[] containerPropNames = {"Items", "Rows"};
1171 static Type GetContainerType (ControlBuilder builder)
1173 TemplateBuilder tb = builder as TemplateBuilder;
1174 if (tb != null && tb.ContainerType != null)
1175 return tb.ContainerType;
1177 Type type = builder.BindingContainerType;
1180 if (typeof (IDataItemContainer).IsAssignableFrom (type))
1184 PropertyInfo prop = GetContainerProperty (type, containerPropNames);
1188 Type ptype = prop.PropertyType;
1189 if (!typeof (ICollection).IsAssignableFrom (ptype))
1192 prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
1196 return prop.PropertyType;
1199 CodeMemberMethod CreateDBMethod (ControlBuilder builder, string name, Type container, Type target)
1201 CodeMemberMethod method = new CodeMemberMethod ();
1202 method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1204 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
1205 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
1207 CodeTypeReference containerRef = new CodeTypeReference (container);
1208 CodeTypeReference targetRef = new CodeTypeReference (target);
1210 CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
1211 decl.Name = "Container";
1212 decl.Type = containerRef;
1213 method.Statements.Add (decl);
1215 decl = new CodeVariableDeclarationStatement();
1216 decl.Name = "target";
1217 decl.Type = targetRef;
1218 method.Statements.Add (decl);
1220 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1221 CodeAssignStatement assign = new CodeAssignStatement ();
1222 assign.Left = targetExpr;
1223 assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
1224 method.Statements.Add (AddLinePragma (assign, builder));
1226 assign = new CodeAssignStatement ();
1227 assign.Left = new CodeVariableReferenceExpression ("Container");
1228 assign.Right = new CodeCastExpression (containerRef,
1229 new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
1230 method.Statements.Add (AddLinePragma (assign, builder));
1235 void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
1237 if (db.Code == null || db.Code.Trim () == "")
1241 CreateField (db, false);
1243 string dbMethodName = "__DataBind_" + db.ID;
1244 // Add the method that builds the DataBoundLiteralControl
1245 InitMethod (db, false, false);
1246 CodeMemberMethod method = db.method;
1247 AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
1248 method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1250 // Add the DataBind handler
1251 method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
1253 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1254 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1255 invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
1256 invoke.Parameters.Add (new CodePrimitiveExpression (0));
1258 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
1259 tostring.Method = new CodeMethodReferenceExpression (
1260 new CodeTypeReferenceExpression (typeof (Convert)),
1262 tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
1263 invoke.Parameters.Add (tostring);
1264 method.Statements.Add (AddLinePragma (invoke, builder));
1266 mainClass.Members.Add (method);
1268 AddChildCall (builder, db);
1271 void FlushText (ControlBuilder builder, StringBuilder sb)
1273 if (sb.Length > 0) {
1274 AddLiteralSubObject (builder, sb.ToString ());
1279 protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
1282 bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
1284 if (!isTemplate && !inTemplate) {
1285 CreateField (builder, true);
1286 } else if (!isTemplate) {
1287 bool doCheck = false;
1290 bool singleInstance = false;
1291 ControlBuilder pb = builder.parentBuilder;
1292 TemplateBuilder tpb;
1293 while (pb != null) {
1294 tpb = pb as TemplateBuilder;
1296 pb = pb.parentBuilder;
1300 if (tpb.TemplateInstance == TemplateInstance.Single)
1301 singleInstance = true;
1305 if (!singleInstance)
1307 builder.ID = builder.GetNextID (null);
1312 CreateField (builder, doCheck);
1315 InitMethod (builder, isTemplate, childrenAsProperties);
1316 if (!isTemplate || builder.GetType () == typeof (RootBuilder))
1317 CreateAssignStatementsFromAttributes (builder);
1319 if (builder.Children != null && builder.Children.Count > 0) {
1320 ArrayList templates = null;
1322 StringBuilder sb = new StringBuilder ();
1323 foreach (object b in builder.Children) {
1325 sb.Append ((string) b);
1329 FlushText (builder, sb);
1330 if (b is ObjectTagBuilder) {
1331 ProcessObjectTag ((ObjectTagBuilder) b);
1335 StringPropertyBuilder pb = b as StringPropertyBuilder;
1337 if (pb.Children != null && pb.Children.Count > 0) {
1338 StringBuilder asb = new StringBuilder ();
1339 foreach (string s in pb.Children)
1341 CodeMemberMethod method = builder.method;
1342 CodeAssignStatement assign = new CodeAssignStatement ();
1343 assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
1344 assign.Right = new CodePrimitiveExpression (asb.ToString ());
1345 method.Statements.Add (AddLinePragma (assign, builder));
1351 if (b is ContentBuilderInternal) {
1352 ContentBuilderInternal cb = (ContentBuilderInternal) b;
1353 CreateControlTree (cb, false, true);
1354 AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
1359 if (b is TemplateBuilder) {
1360 if (templates == null)
1361 templates = new ArrayList ();
1367 if (b is CodeRenderBuilder) {
1368 AddCodeRender (builder, (CodeRenderBuilder) b);
1372 if (b is DataBindingBuilder) {
1373 AddDataBindingLiteral (builder, (DataBindingBuilder) b);
1377 if (b is ControlBuilder) {
1378 ControlBuilder child = (ControlBuilder) b;
1379 CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
1380 AddChildCall (builder, child);
1384 throw new Exception ("???");
1387 FlushText (builder, sb);
1389 if (templates != null) {
1390 foreach (TemplateBuilder b in templates) {
1391 CreateControlTree (b, true, false);
1393 if (b.BindingDirection == BindingDirection.TwoWay) {
1394 string extractMethod = CreateExtractValuesMethod (b);
1395 AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
1399 AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
1405 if (builder.defaultPropertyBuilder != null) {
1406 ControlBuilder b = builder.defaultPropertyBuilder;
1407 CreateControlTree (b, false, true);
1408 AddChildCall (builder, b);
1411 if (builder.HasAspCode) {
1412 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1413 m.TargetObject = thisRef;
1414 m.MethodName = builder.renderMethod.Name;
1416 CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
1417 create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
1418 create.TargetObject = thisRef;
1419 create.MethodName = builder.renderMethod.Name;
1421 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1422 invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
1423 invoke.Parameters.Add (create);
1425 builder.methodStatements.Add (invoke);
1429 if (builder is RootBuilder)
1430 if (!String.IsNullOrEmpty (parser.MetaResourceKey))
1431 AssignPropertiesFromResources (builder, parser.BaseType, parser.MetaResourceKey);
1433 if ((!isTemplate || builder is RootBuilder) && builder.attribs != null && builder.attribs ["meta:resourcekey"] != null)
1434 CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
1437 if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
1438 builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1441 protected internal override void CreateMethods ()
1443 base.CreateMethods ();
1445 CreateProperties ();
1446 CreateControlTree (parser.RootBuilder, false, false);
1447 CreateFrameworkInitializeMethod ();
1450 void CallBaseFrameworkInitialize (CodeMemberMethod method)
1452 CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
1453 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
1454 method.Statements.Add (invoke);
1457 void CreateFrameworkInitializeMethod ()
1459 CodeMemberMethod method = new CodeMemberMethod ();
1460 method.Name = "FrameworkInitialize";
1461 method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1462 PrependStatementsToFrameworkInitialize (method);
1463 CallBaseFrameworkInitialize (method);
1464 AppendStatementsToFrameworkInitialize (method);
1465 mainClass.Members.Add (method);
1468 protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
1472 protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
1474 if (!parser.EnableViewState) {
1475 CodeAssignStatement stmt = new CodeAssignStatement ();
1476 stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
1477 stmt.Right = new CodePrimitiveExpression (false);
1478 method.Statements.Add (stmt);
1481 CodeMethodReferenceExpression methodExpr;
1482 methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
1483 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
1484 method.Statements.Add (new CodeExpressionStatement (expr));
1487 protected override void AddApplicationAndSessionObjects ()
1489 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
1490 CreateFieldForObject (tag.Type, tag.ObjectID);
1491 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
1494 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
1495 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
1499 protected void ProcessObjectTag (ObjectTagBuilder tag)
1501 string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
1502 CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
1505 void CreateProperties ()
1507 if (!parser.AutoEventWireup) {
1508 CreateAutoEventWireup ();
1510 CreateAutoHandlers ();
1513 CreateApplicationInstance ();
1516 void CreateApplicationInstance ()
1518 CodeMemberProperty prop = new CodeMemberProperty ();
1519 Type appType = typeof (HttpApplication);
1520 prop.Type = new CodeTypeReference (appType);
1521 prop.Name = "ApplicationInstance";
1522 prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
1524 CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
1526 propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
1528 CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
1529 prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
1531 if (partialClass != null)
1532 partialClass.Members.Add (prop);
1535 mainClass.Members.Add (prop);
1538 void CreateAutoHandlers ()
1540 // Create AutoHandlers property
1541 CodeMemberProperty prop = new CodeMemberProperty ();
1542 prop.Type = new CodeTypeReference (typeof (int));
1543 prop.Name = "AutoHandlers";
1544 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1546 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
1547 CodeFieldReferenceExpression fldRef ;
1548 fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
1549 ret.Expression = fldRef;
1550 prop.GetStatements.Add (ret);
1551 prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
1554 CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
1555 prop.CustomAttributes.Add (attr);
1558 mainClass.Members.Add (prop);
1560 // Add the __autoHandlers field
1561 CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
1562 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
1563 mainClass.Members.Add (fld);
1566 void CreateAutoEventWireup ()
1568 // The getter returns false
1569 CodeMemberProperty prop = new CodeMemberProperty ();
1570 prop.Type = new CodeTypeReference (typeof (bool));
1571 prop.Name = "SupportAutoEvents";
1572 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1573 prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
1574 mainClass.Members.Add (prop);
1578 protected virtual string HandleUrlProperty (string str, MemberInfo member)
1584 TypeConverter GetConverterForMember (MemberInfo member)
1586 TypeConverterAttribute tca = null;
1590 attrs = member.GetCustomAttributes (typeof (TypeConverterAttribute), true);
1591 if (attrs.Length > 0)
1592 tca = attrs [0] as TypeConverterAttribute;
1594 attrs = member.GetCustomAttributes (true);
1596 foreach (object attr in attrs) {
1597 tca = attr as TypeConverterAttribute;
1607 string typeName = tca.ConverterTypeName;
1608 if (typeName == null || typeName.Length == 0)
1613 t = HttpApplication.LoadType (typeName);
1614 } catch (Exception) {
1621 return (TypeConverter) Activator.CreateInstance (t);
1624 CodeExpression CreateNullableExpression (Type type, CodeExpression inst, bool nullable)
1630 return new CodeObjectCreateExpression (
1632 new CodeExpression[] {inst}
1639 bool SafeCanConvertFrom (Type type, TypeConverter cvt)
1642 return cvt.CanConvertFrom (type);
1643 } catch (NotImplementedException) {
1648 bool SafeCanConvertTo (Type type, TypeConverter cvt)
1651 return cvt.CanConvertTo (type);
1652 } catch (NotImplementedException) {
1657 CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
1659 TypeConverter cvt = GetConverterForMember (member);
1660 if (cvt != null && !SafeCanConvertFrom (typeof (string), cvt))
1663 object convertedFromAttr = null;
1664 bool preConverted = false;
1665 if (cvt != null && str != null) {
1666 convertedFromAttr = cvt.ConvertFromInvariantString (str);
1667 if (convertedFromAttr != null) {
1668 type = convertedFromAttr.GetType ();
1669 preConverted = true;
1673 bool wasNullable = false;
1674 Type originalType = type;
1676 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
1677 Type[] types = type.GetGenericArguments();
1678 originalType = type;
1679 type = types[0]; // we're interested only in the first type here
1684 if (type == typeof (string)) {
1686 return CreateNullableExpression (originalType,
1687 new CodePrimitiveExpression ((string) convertedFromAttr),
1691 object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
1692 if (urlAttr.Length != 0)
1693 str = HandleUrlProperty (str, member);
1695 return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
1698 if (type == typeof (bool)) {
1700 return CreateNullableExpression (originalType,
1701 new CodePrimitiveExpression ((bool) convertedFromAttr),
1704 if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
1705 return CreateNullableExpression (originalType, new CodePrimitiveExpression (true), wasNullable);
1706 else if (InvariantCompareNoCase (str, "false"))
1707 return CreateNullableExpression (originalType, new CodePrimitiveExpression (false), wasNullable);
1709 else if (wasNullable && InvariantCompareNoCase(str, "null"))
1710 return new CodePrimitiveExpression (null);
1713 throw new ParseException (currentLocation,
1714 "Value '" + str + "' is not a valid boolean.");
1718 return new CodePrimitiveExpression (null);
1720 if (type.IsPrimitive)
1721 return CreateNullableExpression (originalType,
1722 new CodePrimitiveExpression (
1723 Convert.ChangeType (preConverted ? convertedFromAttr : str,
1724 type, CultureInfo.InvariantCulture)),
1727 if (type == typeof (string [])) {
1731 subs = (string[])convertedFromAttr;
1733 subs = str.Split (',');
1734 CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
1735 expr.CreateType = new CodeTypeReference (typeof (string));
1736 foreach (string v in subs)
1737 expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
1739 return CreateNullableExpression (originalType, expr, wasNullable);
1742 if (type == typeof (Color)) {
1745 if (!preConverted) {
1746 if (colorConverter == null)
1747 colorConverter = TypeDescriptor.GetConverter (typeof (Color));
1749 if (str.Trim().Length == 0) {
1750 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
1751 return CreateNullableExpression (originalType,
1752 new CodeFieldReferenceExpression (ft, "Empty"),
1757 if (str.IndexOf (',') == -1) {
1758 c = (Color) colorConverter.ConvertFromString (str);
1760 int [] argb = new int [4];
1763 string [] parts = str.Split (',');
1764 int length = parts.Length;
1766 throw new Exception ();
1768 int basei = (length == 4) ? 0 : 1;
1769 for (int i = length - 1; i >= 0; i--) {
1770 argb [basei + i] = (int) Byte.Parse (parts [i]);
1772 c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
1774 } catch (Exception e) {
1775 // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
1776 // TypeConverter for Color fails to ConvertFromString.
1777 // Hence this hack...
1778 if (InvariantCompareNoCase ("LightGrey", str)) {
1779 c = Color.LightGray;
1781 throw new ParseException (currentLocation,
1782 "Color " + str + " is not a valid color.", e);
1786 c = (Color)convertedFromAttr;
1788 if (c.IsKnownColor) {
1789 CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
1790 if (c.IsSystemColor)
1791 type = typeof (SystemColors);
1793 expr.TargetObject = new CodeTypeReferenceExpression (type);
1794 expr.FieldName = c.Name;
1795 return CreateNullableExpression (originalType, expr, wasNullable);
1797 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1798 m.TargetObject = new CodeTypeReferenceExpression (type);
1799 m.MethodName = "FromArgb";
1800 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1801 invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
1802 invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
1803 invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
1804 invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
1805 return CreateNullableExpression (originalType, invoke, wasNullable);
1809 TypeConverter converter = preConverted ? cvt :
1810 wasNullable ? TypeDescriptor.GetConverter (type) :
1811 TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
1813 if (preConverted || (converter != null && SafeCanConvertFrom (typeof (string), converter))) {
1814 object value = preConverted ? convertedFromAttr : converter.ConvertFromInvariantString (str);
1816 if (SafeCanConvertTo (typeof (InstanceDescriptor), converter)) {
1817 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1819 return CreateNullableExpression (originalType, GenerateInstance (idesc, true),
1822 return new CodeCastExpression (type, GenerateInstance (idesc, true));
1825 CodeExpression exp = GenerateObjectInstance (value, false);
1827 return CreateNullableExpression (originalType, exp, wasNullable);
1829 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1830 m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
1831 m.MethodName = "GetConverter";
1832 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1833 CodeTypeReference tref = new CodeTypeReference (type);
1834 invoke.Parameters.Add (new CodeTypeOfExpression (tref));
1836 invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
1837 invoke.Parameters.Add (new CodePrimitiveExpression (str));
1840 return CreateNullableExpression (originalType, invoke, wasNullable);
1842 return new CodeCastExpression (type, invoke);
1845 Console.WriteLine ("Unknown type: " + type + " value: " + str);
1847 return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
1850 CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
1852 CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
1854 foreach (object ob in idesc.Arguments) {
1855 CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
1856 if (exp == null) return null;
1857 parameters [n++] = exp;
1860 switch (idesc.MemberInfo.MemberType) {
1861 case MemberTypes.Constructor:
1862 CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
1863 return new CodeObjectCreateExpression (tob, parameters);
1865 case MemberTypes.Method:
1866 CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1867 return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
1869 case MemberTypes.Field:
1870 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1871 return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
1873 case MemberTypes.Property:
1874 CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1875 return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
1877 throw new ParseException (currentLocation, "Invalid instance type.");
1880 CodeExpression GenerateObjectInstance (object value, bool throwOnError)
1883 return new CodePrimitiveExpression (null);
1885 if (value is System.Type) {
1886 CodeTypeReference tref = new CodeTypeReference (value.ToString ());
1887 return new CodeTypeOfExpression (tref);
1890 Type t = value.GetType ();
1892 if (t.IsPrimitive || value is string)
1893 return new CodePrimitiveExpression (value);
1896 Array ar = (Array) value;
1897 CodeExpression[] items = new CodeExpression [ar.Length];
1898 for (int n=0; n<ar.Length; n++) {
1899 CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
1900 if (exp == null) return null;
1903 return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
1906 TypeConverter converter = TypeDescriptor.GetConverter (t);
1907 if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
1908 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1909 return GenerateInstance (idesc, throwOnError);
1912 InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
1913 if (desc != null) return GenerateInstance (desc, throwOnError);
1916 throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
1921 InstanceDescriptor GetDefaultInstanceDescriptor (object value)
1923 if (value is System.Web.UI.WebControls.Unit) {
1924 System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
1925 ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
1926 BindingFlags.Instance | BindingFlags.Public,
1928 new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
1931 return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
1934 if (value is System.Web.UI.WebControls.FontUnit) {
1935 System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
1937 Type cParamType = null;
1938 object cParam = null;
1941 case FontSize.AsUnit:
1942 case FontSize.NotSet:
1943 cParamType = typeof (System.Web.UI.WebControls.Unit);
1948 cParamType = typeof (string);
1949 cParam = s.Type.ToString ();
1953 ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
1954 BindingFlags.Instance | BindingFlags.Public,
1956 new Type[] {cParamType},
1959 return new InstanceDescriptor (c, new object[] {cParam});