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.Text.RegularExpressions;
47 using System.Web.Configuration;
50 namespace System.Web.Compilation
52 class TemplateControlCompiler : BaseCompiler
54 static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
55 BindingFlags.Instance | BindingFlags.IgnoreCase;
57 TemplateControlParser parser;
59 ILocation currentLocation;
61 static TypeConverter colorConverter;
63 internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
66 static Regex bindRegex = new Regex (@"Bind\s*\(""(.*?)""\)\s*%>", RegexOptions.Compiled);
69 public TemplateControlCompiler (TemplateControlParser parser)
75 protected void EnsureID (ControlBuilder builder)
77 if (builder.ID == null || builder.ID.Trim () == "")
78 builder.ID = builder.GetNextID (null);
81 void CreateField (ControlBuilder builder, bool check)
83 if (builder == null || builder.ID == null || builder.ControlType == null)
86 if (partialNameOverride [builder.ID] != null)
89 MemberAttributes ma = MemberAttributes.Family;
90 currentLocation = builder.location;
91 if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType, ref ma))
92 return; // The field or property already exists in a base class and is accesible.
94 CodeMemberField field;
95 field = new CodeMemberField (builder.ControlType.FullName, builder.ID);
96 field.Attributes = ma;
98 if (partialClass != null)
99 partialClass.Members.Add (field);
102 mainClass.Members.Add (field);
105 bool CheckBaseFieldOrProperty (string id, Type type, ref MemberAttributes ma)
107 FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);
110 if (fld == null || fld.IsPrivate) {
111 PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
113 MethodInfo setm = prop.GetSetMethod (true);
115 other = prop.PropertyType;
118 other = fld.FieldType;
124 if (!other.IsAssignableFrom (type)) {
126 ma |= MemberAttributes.New;
129 string msg = String.Format ("The base class includes the field '{0}', but its " +
130 "type '{1}' is not compatible with {2}",
132 throw new ParseException (currentLocation, msg);
139 void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr)
141 if (!builder.haveParserVariable) {
142 CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
144 p.Type = new CodeTypeReference (typeof (IParserAccessor));
145 p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
146 builder.methodStatements.Add (p);
147 builder.haveParserVariable = true;
150 CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
151 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
152 invoke.Parameters.Add (expr);
153 builder.methodStatements.Add (invoke);
156 void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
158 string tailname = ((builder is RootBuilder) ? "Tree" : ("_" + builder.ID));
159 CodeMemberMethod method = new CodeMemberMethod ();
160 builder.method = method;
161 builder.methodStatements = method.Statements;
163 method.Name = "__BuildControl" + tailname;
164 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
165 Type type = builder.ControlType;
167 /* in the case this is the __BuildControlTree
168 * method, allow subclasses to insert control
170 if (builder is RootBuilder)
171 AddStatementsToInitMethod (method);
173 if (builder.HasAspCode) {
174 CodeMemberMethod renderMethod = new CodeMemberMethod ();
175 builder.renderMethod = renderMethod;
176 renderMethod.Name = "__Render" + tailname;
177 renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
178 CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
179 arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
180 arg1.Name = "__output";
181 CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
182 arg2.Type = new CodeTypeReference (typeof (Control));
183 arg2.Name = "parameterContainer";
184 renderMethod.Parameters.Add (arg1);
185 renderMethod.Parameters.Add (arg2);
186 mainClass.Members.Add (renderMethod);
189 if (childrenAsProperties || builder.ControlType == null) {
191 if (builder is RootBuilder)
192 typeString = parser.ClassName;
194 if (builder.ControlType != null && builder.isProperty &&
195 !typeof (ITemplate).IsAssignableFrom (builder.ControlType))
196 typeString = builder.ControlType.FullName;
198 typeString = "System.Web.UI.Control";
201 method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
204 if (typeof (Control).IsAssignableFrom (type))
205 method.ReturnType = new CodeTypeReference (typeof (Control));
207 // _ctrl = new $controlType ($parameters);
209 CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (type);
211 object [] atts = type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true);
212 if (atts != null && atts.Length > 0) {
213 ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
215 newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
216 } else if (builder is DataBindingBuilder) {
217 newExpr.Parameters.Add (new CodePrimitiveExpression (0));
218 newExpr.Parameters.Add (new CodePrimitiveExpression (1));
221 method.Statements.Add (new CodeVariableDeclarationStatement (builder.ControlType, "__ctrl"));
222 CodeAssignStatement assign = new CodeAssignStatement ();
223 assign.Left = ctrlVar;
224 assign.Right = newExpr;
225 method.Statements.Add (assign);
227 // this.$builderID = _ctrl;
229 CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
230 builderID.TargetObject = thisRef;
231 builderID.FieldName = builder.ID;
232 assign = new CodeAssignStatement ();
233 assign.Left = builderID;
234 assign.Right = ctrlVar;
235 method.Statements.Add (assign);
236 if (typeof (UserControl).IsAssignableFrom (type)) {
237 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
238 mref.TargetObject = builderID;
239 mref.MethodName = "InitializeAsUserControl";
240 CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
241 initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
242 method.Statements.Add (initAsControl);
246 // _ctrl.SkinID = $value
247 // _ctrl.ApplyStyleSheetSkin (this);
249 // the SkinID assignment needs to come
250 // before the call to
251 // ApplyStyleSheetSkin, for obvious
252 // reasons. We skip SkinID in
253 // CreateAssignStatementsFromAttributes
256 if (builder.attribs != null) {
257 string skinid = builder.attribs ["skinid"] as string;
259 CreateAssignStatementFromAttribute (builder, "skinid");
261 if (typeof (WebControl).IsAssignableFrom (type)) {
262 CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
263 if (typeof (Page).IsAssignableFrom (parser.BaseType))
264 applyStyleSheetSkin.Parameters.Add (thisRef);
266 applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
267 method.Statements.Add (applyStyleSheetSkin);
272 if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
273 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (thisRef, "ContentPlaceHolders");
274 CodeMethodInvokeExpression addPlaceholder = new CodeMethodInvokeExpression (prop, "Add");
275 addPlaceholder.Parameters.Add (ctrlVar);
276 method.Statements.Add (addPlaceholder);
279 CodeConditionStatement condStatement;
281 // Add the __Template_* field
282 CodeMemberField fld = new CodeMemberField (typeof (ITemplate), "__Template_" + builder.ID);
283 fld.Attributes = MemberAttributes.Private;
284 mainClass.Members.Add (fld);
286 CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
287 templateID.TargetObject = thisRef;
288 templateID.FieldName = "__Template_" + builder.ID;
290 // if ((this.ContentTemplates != null)) {
291 // this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
294 CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
295 contentTemplates.TargetObject = thisRef;
296 contentTemplates.FieldName = "ContentTemplates";
298 CodeIndexerExpression indexer = new CodeIndexerExpression ();
299 indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
300 indexer.Indices.Add (new CodePrimitiveExpression (builder.ID));
302 assign = new CodeAssignStatement ();
303 assign.Left = templateID;
304 assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);
306 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
307 CodeBinaryOperatorType.IdentityInequality,
308 new CodePrimitiveExpression (null)),
311 method.Statements.Add (condStatement);
313 // if ((this.__Template_mainContent != null)) {
314 // this.__Template_mainContent.InstantiateIn(__ctrl);
316 // and also set things up such that any additional code ends up in:
321 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
322 methodRef.TargetObject = templateID;
323 methodRef.MethodName = "InstantiateIn";
325 CodeMethodInvokeExpression instantiateInInvoke;
326 instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);
328 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
329 CodeBinaryOperatorType.IdentityInequality,
330 new CodePrimitiveExpression (null)),
331 new CodeExpressionStatement (instantiateInInvoke));
332 method.Statements.Add (condStatement);
334 // this is the bit that causes the following stuff to end up in the else { }
335 builder.methodStatements = condStatement.FalseStatements;
337 // __ctrl.TemplateControl = this;
338 assign = new CodeAssignStatement ();
339 assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
340 assign.Right = thisRef;
342 method.Statements.Add (assign);
347 mainClass.Members.Add (method);
350 protected virtual void AddStatementsToInitMethod (CodeMemberMethod method)
354 void AddLiteralSubObject (ControlBuilder builder, string str)
356 if (!builder.HasAspCode) {
357 CodeObjectCreateExpression expr;
358 expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
359 AddParsedSubObjectStmt (builder, expr);
361 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
362 methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
363 methodRef.MethodName = "Write";
365 CodeMethodInvokeExpression expr;
366 expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
367 builder.renderMethod.Statements.Add (expr);
371 string TrimDB (string value)
373 string str = value.Trim ();
374 str = str.Substring (3);
375 return str.Substring (0, str.Length - 2);
378 string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
380 value = TrimDB (value);
381 CodeMemberMethod method;
382 string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
384 bool need_if = false;
385 value = value.Trim ();
386 if (StrUtils.StartsWith (value, "Bind")) {
387 value = "Eval" + value.Substring (4);
392 method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
394 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
396 // This should be a CodePropertyReferenceExpression for properties... but it works anyway
397 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
400 if (type == typeof (string)) {
401 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
402 CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
403 tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
404 tostring.Parameters.Add (new CodeSnippetExpression (value));
407 CodeSnippetExpression snippet = new CodeSnippetExpression (value);
408 expr = new CodeCastExpression (type, snippet);
411 CodeAssignStatement assign = new CodeAssignStatement (field, expr);
414 CodeExpression page = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Page");
415 CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
416 CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
417 CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
418 method.Statements.Add (ccs);
422 method.Statements.Add (assign);
424 mainClass.Members.Add (method);
428 void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
430 CodeMemberMethod method = builder.method;
431 bool isWritable = IsWritablePropertyOrField (member);
432 if (isDataBound && isWritable) {
433 string dbMethodName = DataBoundProperty (builder, type, var_name, att);
434 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
438 else if (isExpression && isWritable) {
439 AddExpressionAssign (method, member, type, var_name, att);
444 CodeAssignStatement assign = new CodeAssignStatement ();
445 assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
446 currentLocation = builder.location;
447 assign.Right = GetExpressionFromString (type, att, member);
449 method.Statements.Add (assign);
452 bool IsDataBound (string value)
454 if (value == null || value == "")
457 string str = value.Trim ();
458 return (StrUtils.StartsWith (str, "<%#") && StrUtils.EndsWith (str, "%>"));
462 bool IsExpression (string value)
464 if (value == null || value == "")
466 string str = value.Trim ();
467 return (StrUtils.StartsWith (str, "<%$") && StrUtils.EndsWith (str, "%>"));
470 void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
472 string str = value.Trim ();
473 str = str.Substring (3).Trim (); // eats "<%#"
474 if (StrUtils.StartsWith (str, "Bind")) {
475 Match match = bindRegex.Match (str);
477 string bindingName = match.Groups [1].Value;
479 TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
480 if (templateBuilder == null || templateBuilder.BindingDirection == BindingDirection.OneWay)
481 throw new HttpException ("Bind expression not allowed in this context.");
483 string id = builder.attribs ["ID"] as string;
485 throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
487 templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
494 static bool InvariantCompare (string a, string b)
496 return (0 == String.Compare (a, b, false, CultureInfo.InvariantCulture));
500 static bool InvariantCompareNoCase (string a, string b)
502 return (0 == String.Compare (a, b, true, CultureInfo.InvariantCulture));
505 static MemberInfo GetFieldOrProperty (Type type, string name)
507 MemberInfo member = null;
509 member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
516 member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
522 static bool IsWritablePropertyOrField (MemberInfo member)
524 PropertyInfo pi = member as PropertyInfo;
527 FieldInfo fi = member as FieldInfo;
529 return !fi.IsInitOnly;
530 throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
533 bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
534 string attValue, string prefix)
536 int hyphen = id.IndexOf ('-');
537 bool isPropertyInfo = (member is PropertyInfo);
538 bool isDataBound = IsDataBound (attValue);
540 bool isExpression = !isDataBound && IsExpression (attValue);
542 bool isExpression = false;
545 if (isPropertyInfo) {
546 type = ((PropertyInfo) member).PropertyType;
548 type = ((FieldInfo) member).FieldType;
551 if (InvariantCompareNoCase (member.Name, id)) {
554 RegisterBindingInfo (builder, member.Name, ref attValue);
557 if (!IsWritablePropertyOrField (member))
560 AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
567 string prop_field = id.Replace ("-", ".");
568 string [] parts = prop_field.Split (new char [] {'.'});
569 int length = parts.Length;
570 if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
574 MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
575 if (sub_member == null)
578 string new_prefix = prefix + parts [0] + ".";
579 string new_id = id.Substring (hyphen + 1);
580 return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
583 MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
584 if (!(subpf is PropertyInfo))
587 PropertyInfo subprop = (PropertyInfo) subpf;
588 if (subprop.CanWrite == false)
591 bool is_bool = (subprop.PropertyType == typeof (bool));
592 if (!is_bool && attValue == null)
593 return false; // Font-Size -> Font-Size="" as html
595 string val = attValue;
596 if (attValue == null && is_bool)
597 val = "true"; // Font-Bold <=> Font-Bold="true"
599 if (isDataBound) RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
601 AddCodeForPropertyOrField (builder, subprop.PropertyType,
602 prefix + member.Name + "." + subprop.Name,
603 val, subprop, isDataBound, isExpression);
609 void AddExpressionAssign (CodeMemberMethod method, MemberInfo member, Type type, string name, string value)
611 CodeAssignStatement assign = new CodeAssignStatement ();
612 assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
614 // First let's find the correct expression builder
615 string expr = value.Substring (3, value.Length - 5).Trim ();
616 int colon = expr.IndexOf (':');
619 string prefix = expr.Substring (0, colon).Trim ();
621 System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration ("");
624 CompilationSection cs = (CompilationSection)config.GetSection ("system.web/compilation");
627 if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
630 System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
633 string builderType = ceb.Type;
637 t = System.Type.GetType (builderType, true);
638 } catch (Exception e) {
639 throw new HttpException (
640 String.Format ("Failed to load expression builder type `{0}'", builderType), e);
643 if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
644 throw new HttpException (
646 "Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder",
649 System.Web.Compilation.ExpressionBuilder eb = null;
651 ExpressionBuilderContext ctx;
654 eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
655 ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
656 parsedData = eb.ParseExpression (expr.Substring (colon + 1).Trim (), type, ctx);
657 } catch (Exception e) {
658 throw new HttpException (
659 String.Format ("Failed to create an instance of type `{0}'", builderType), e);
661 // FIXME: create and pass an instance of BoundPropertyEntry
662 CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
663 convert.Method = new CodeMethodReferenceExpression (
664 new CodeTypeReferenceExpression (typeof(Convert)),
666 convert.Parameters.Add (eb.GetCodeExpression (null, parsedData, ctx));
667 convert.Parameters.Add (
668 new CodeFieldReferenceExpression (
669 new CodeTypeReferenceExpression ("System.Globalization.CultureInfo"),
671 assign.Right = convert;
673 method.Statements.Add (assign);
676 void AssignPropertyFromResources (CodeMemberMethod method, MemberInfo mi, string attvalue, string varname)
678 string resname = String.Format ("{0}.{1}", attvalue, mi.Name);
679 bool isProperty = mi.MemberType == MemberTypes.Property;
680 bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
682 if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
685 Type member_type = null;
687 PropertyInfo pi = mi as PropertyInfo;
688 member_type = pi.PropertyType;
689 } else if (isField) {
690 FieldInfo fi = mi as FieldInfo;
691 member_type = fi.FieldType;
692 } else // should never happen
695 // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
696 string inputFile = parser.InputFile;
697 string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
699 if (StrUtils.StartsWith (inputFile, physPath))
700 inputFile = parser.InputFile.Substring (physPath.Length - 1);
704 object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
708 CodeAssignStatement assign = new CodeAssignStatement ();
709 assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
710 CodeMethodInvokeExpression getlro = new CodeMethodInvokeExpression (
711 new CodeThisReferenceExpression (),
712 "GetLocalResourceObject",
713 new CodeExpression [] { new CodePrimitiveExpression (resname) });
715 CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
716 convert.Method = new CodeMethodReferenceExpression (
717 new CodeTypeReferenceExpression (typeof(System.Convert)),
719 convert.Parameters.Add (getlro);
720 assign.Right = convert;
722 // assign.Left = new CodeVariableReferenceExpression (varname);
723 // assign.Right = new CodeMethodInvokeExpression (
724 // new CodeThisReferenceExpression (),
725 // "GetLocalResourceObject",
726 // new CodeExpression [] { new CodePrimitiveExpression (resname) });
727 // method.Statements.Add (assign);
729 // // if (localResourceObject != null && localResourceObject.GetType() == typeof(member_type))
730 // CodeConditionStatement ccs = new CodeConditionStatement ();
731 // CodeBinaryOperatorExpression exp1 = new CodeBinaryOperatorExpression (
732 // new CodeVariableReferenceExpression (varname),
733 // CodeBinaryOperatorType.IdentityInequality,
734 // new CodePrimitiveExpression (null));
736 // CodeBinaryOperatorExpression exp2 = new CodeBinaryOperatorExpression (
737 // new CodeMethodInvokeExpression (
738 // new CodeVariableReferenceExpression (varname),
740 // new CodeExpression [] {}),
741 // CodeBinaryOperatorType.IdentityEquality,
742 // new CodeTypeOfExpression (
743 // new CodeTypeReference (member_type.ToString ())));
744 // ccs.Condition = new CodeBinaryOperatorExpression (
746 // CodeBinaryOperatorType.BooleanAnd,
749 // // ctrlVar.Property = (member_type)obj;
750 // assign = new CodeAssignStatement ();
751 // assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
752 // assign.Right = new CodeCastExpression (
753 // member_type.ToString (),
754 // new CodeVariableReferenceExpression (varname));
755 // ccs.TrueStatements.Add (assign);
756 method.Statements.Add (assign);
759 void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
761 if (attvalue == null || attvalue.Length == 0)
764 Type controlType = builder.ControlType;
765 if (controlType == null)
768 // object obj = null;
770 // Process all public fields and properties of the control. We don't use GetMembers to make the code
772 FieldInfo [] fields = controlType.GetFields (
773 BindingFlags.Instance | BindingFlags.Static |
774 BindingFlags.Public | BindingFlags.FlattenHierarchy);
775 PropertyInfo [] properties = controlType.GetProperties (
776 BindingFlags.Instance | BindingFlags.Static |
777 BindingFlags.Public | BindingFlags.FlattenHierarchy);
779 if (fields.Length > 0 || properties.Length > 0) {
780 CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement (
782 "localResourceObject",
783 new CodePrimitiveExpression (null));
784 builder.method.Statements.Add (cvds);
787 foreach (FieldInfo fi in fields)
788 AssignPropertyFromResources (builder.method, fi, attvalue, "localResourceObject");
789 foreach (PropertyInfo pi in properties)
790 AssignPropertyFromResources (builder.method, pi, attvalue, "localResourceObject");
794 void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
796 //"__ctrl.{0} += new {1} (this.{2});"
797 CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
799 CodeDelegateCreateExpression create;
800 create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
802 CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
803 method.Statements.Add (attach);
806 void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
808 EventInfo [] ev_info = null;
809 Type type = builder.ControlType;
811 string attvalue = builder.attribs [id] as string;
812 if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
814 ev_info = type.GetEvents ();
816 string id_as_event = id.Substring (2);
817 foreach (EventInfo ev in ev_info){
818 if (InvariantCompareNoCase (ev.Name, id_as_event)){
819 AddEventAssign (builder.method,
831 if (id.ToLower () == "meta:resourcekey") {
832 AssignPropertiesFromResources (builder, attvalue);
837 int hyphen = id.IndexOf ('-');
840 alt_id = id.Substring (0, hyphen);
842 MemberInfo fop = GetFieldOrProperty (type, alt_id);
844 if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
848 if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
849 throw new ParseException (builder.location, "Unrecognized attribute: " + id);
852 CodeMemberMethod method = builder.method;
853 bool databound = IsDataBound (attvalue);
856 val = attvalue.Substring (3);
857 val = val.Substring (0, val.Length - 2);
858 CreateDBAttributeMethod (builder, id, val);
860 CodeCastExpression cast;
861 CodeMethodReferenceExpression methodExpr;
862 CodeMethodInvokeExpression expr;
864 cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
865 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
866 expr = new CodeMethodInvokeExpression (methodExpr);
867 expr.Parameters.Add (new CodePrimitiveExpression (id));
868 expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
869 method.Statements.Add (expr);
874 protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
876 this.dataBoundAtts = 0;
877 IDictionary atts = builder.attribs;
878 if (atts == null || atts.Count == 0)
881 foreach (string id in atts.Keys) {
882 if (InvariantCompareNoCase (id, "runat"))
886 /* we skip SkinID here as it's assigned in BuildControlTree */
887 if (InvariantCompareNoCase (id, "skinid"))
890 CreateAssignStatementFromAttribute (builder, id);
894 void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
896 if (code == null || code.Trim () == "")
899 string id = builder.GetNextID (null);
900 string dbMethodName = "__DataBind_" + id;
901 CodeMemberMethod method = builder.method;
902 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
904 method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
905 CodeCastExpression cast;
906 CodeMethodReferenceExpression methodExpr;
907 CodeMethodInvokeExpression expr;
909 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
910 cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
911 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
912 expr = new CodeMethodInvokeExpression (methodExpr);
913 expr.Parameters.Add (new CodePrimitiveExpression (attr));
914 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
915 tostring.Method = new CodeMethodReferenceExpression (
916 new CodeTypeReferenceExpression (typeof (Convert)),
918 tostring.Parameters.Add (new CodeSnippetExpression (code));
919 expr.Parameters.Add (tostring);
920 method.Statements.Add (expr);
921 mainClass.Members.Add (method);
924 void AddRenderControl (ControlBuilder builder)
926 CodeIndexerExpression indexer = new CodeIndexerExpression ();
927 indexer.TargetObject = new CodePropertyReferenceExpression (
928 new CodeArgumentReferenceExpression ("parameterContainer"),
931 indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
933 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
934 invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
935 builder.renderMethod.Statements.Add (invoke);
936 builder.renderIndex++;
939 protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
941 if (parent == null || child == null)
943 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
944 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
946 object [] atts = null;
948 if (child.ControlType != null)
949 child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
950 if (atts != null && atts.Length > 0) {
951 PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
952 CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
953 CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
954 build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
955 build.Parameters.Add (new CodePrimitiveExpression (child.ID));
958 build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
961 build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
963 build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
964 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
965 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
966 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
967 build.Parameters.Add (new CodeDelegateCreateExpression (
968 new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
969 thisRef, child.method.Name));
971 parent.methodStatements.Add (build);
972 if (parent.HasAspCode)
973 AddRenderControl (parent);
977 if (child.isProperty || parent.ChildrenAsProperties) {
978 expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
979 parent.methodStatements.Add (expr);
983 parent.methodStatements.Add (expr);
984 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
985 if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
986 AddParsedSubObjectStmt (parent, field);
988 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
989 invoke.Parameters.Add (field);
990 parent.methodStatements.Add (invoke);
993 if (parent.HasAspCode)
994 AddRenderControl (parent);
997 void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
999 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1001 CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1002 newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1004 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1005 newCompiled.Parameters.Add (newBuild);
1007 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1008 method.Statements.Add (assign);
1012 void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
1014 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1016 CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1017 newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1019 CodeObjectCreateExpression newExtract = new CodeObjectCreateExpression (typeof (ExtractTemplateValuesMethod));
1020 newExtract.Parameters.Add (new CodeMethodReferenceExpression (thisRef, extractMethodName));
1022 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
1023 newCompiled.Parameters.Add (newBuild);
1024 newCompiled.Parameters.Add (newExtract);
1026 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1027 method.Statements.Add (assign);
1030 string CreateExtractValuesMethod (TemplateBuilder builder)
1032 CodeMemberMethod method = new CodeMemberMethod ();
1033 method.Name = "__ExtractValues_" + builder.ID;
1034 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1035 method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
1037 CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
1038 arg.Type = new CodeTypeReference (typeof (Control));
1039 arg.Name = "__container";
1040 method.Parameters.Add (arg);
1041 mainClass.Members.Add (method);
1043 CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
1044 newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
1045 method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
1046 CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
1048 if (builder.Bindings != null) {
1049 Hashtable hash = new Hashtable ();
1050 foreach (TemplateBinding binding in builder.Bindings) {
1051 CodeConditionStatement sif;
1052 CodeVariableReferenceExpression control;
1053 CodeAssignStatement assign;
1055 if (hash [binding.ControlId] == null) {
1057 CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
1058 method.Statements.Add (dec);
1059 CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
1060 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
1061 invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
1063 assign = new CodeAssignStatement ();
1064 control = new CodeVariableReferenceExpression (binding.ControlId);
1065 assign.Left = control;
1066 assign.Right = new CodeCastExpression (binding.ControlType, invoke);
1067 method.Statements.Add (assign);
1069 sif = new CodeConditionStatement ();
1070 sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
1072 method.Statements.Add (sif);
1074 hash [binding.ControlId] = sif;
1077 sif = (CodeConditionStatement) hash [binding.ControlId];
1078 control = new CodeVariableReferenceExpression (binding.ControlId);
1079 assign = new CodeAssignStatement ();
1080 assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
1081 assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
1082 sif.TrueStatements.Add (assign);
1086 method.Statements.Add (new CodeMethodReturnStatement (tableExp));
1090 void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
1092 CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1093 newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1095 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1096 newCompiled.Parameters.Add (newBuild);
1098 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
1099 invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
1100 invoke.Parameters.Add (newCompiled);
1102 method.Statements.Add (invoke);
1106 void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
1108 if (cr.Code == null || cr.Code.Trim () == "")
1112 CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
1113 parent.renderMethod.Statements.Add (code);
1117 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
1118 expr.Method = new CodeMethodReferenceExpression (
1119 new CodeArgumentReferenceExpression ("__output"),
1122 expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
1123 parent.renderMethod.Statements.Add (expr);
1126 static Type GetContainerType (ControlBuilder builder)
1128 TemplateBuilder tb = builder as TemplateBuilder;
1129 if (tb != null && tb.ContainerType != null)
1130 return tb.ContainerType;
1132 Type type = builder.BindingContainerType;
1134 PropertyInfo prop = type.GetProperty ("Items", noCaseFlags & ~BindingFlags.NonPublic);
1138 Type ptype = prop.PropertyType;
1139 if (!typeof (ICollection).IsAssignableFrom (ptype))
1142 prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
1146 return prop.PropertyType;
1149 CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
1151 CodeMemberMethod method = new CodeMemberMethod ();
1152 method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1154 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
1155 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
1157 CodeTypeReference containerRef = new CodeTypeReference (container);
1158 CodeTypeReference targetRef = new CodeTypeReference (target);
1160 CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
1161 decl.Name = "Container";
1162 decl.Type = containerRef;
1163 method.Statements.Add (decl);
1165 decl = new CodeVariableDeclarationStatement();
1166 decl.Name = "target";
1167 decl.Type = targetRef;
1168 method.Statements.Add (decl);
1170 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1171 CodeAssignStatement assign = new CodeAssignStatement ();
1172 assign.Left = targetExpr;
1173 assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
1174 method.Statements.Add (assign);
1176 assign = new CodeAssignStatement ();
1177 assign.Left = new CodeVariableReferenceExpression ("Container");
1178 assign.Right = new CodeCastExpression (containerRef,
1179 new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
1180 method.Statements.Add (assign);
1185 void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
1187 if (db.Code == null || db.Code.Trim () == "")
1191 CreateField (db, false);
1193 string dbMethodName = "__DataBind_" + db.ID;
1194 // Add the method that builds the DataBoundLiteralControl
1195 InitMethod (db, false, false);
1196 CodeMemberMethod method = db.method;
1197 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
1198 method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1200 // Add the DataBind handler
1201 method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
1203 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1204 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1205 invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
1206 invoke.Parameters.Add (new CodePrimitiveExpression (0));
1208 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
1209 tostring.Method = new CodeMethodReferenceExpression (
1210 new CodeTypeReferenceExpression (typeof (Convert)),
1212 tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
1213 invoke.Parameters.Add (tostring);
1214 method.Statements.Add (invoke);
1216 mainClass.Members.Add (method);
1218 AddChildCall (builder, db);
1221 void FlushText (ControlBuilder builder, StringBuilder sb)
1223 if (sb.Length > 0) {
1224 AddLiteralSubObject (builder, sb.ToString ());
1229 protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
1232 bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
1233 if (!isTemplate && !inTemplate) {
1234 CreateField (builder, true);
1235 } else if (!isTemplate) {
1236 builder.ID = builder.GetNextID (null);
1237 CreateField (builder, false);
1240 InitMethod (builder, isTemplate, childrenAsProperties);
1241 if (!isTemplate || builder.GetType () == typeof (RootBuilder))
1242 CreateAssignStatementsFromAttributes (builder);
1244 if (builder.Children != null && builder.Children.Count > 0) {
1245 ArrayList templates = null;
1247 StringBuilder sb = new StringBuilder ();
1248 foreach (object b in builder.Children) {
1251 sb.Append ((string) b);
1255 FlushText (builder, sb);
1256 if (b is ObjectTagBuilder) {
1257 ProcessObjectTag ((ObjectTagBuilder) b);
1261 StringPropertyBuilder pb = b as StringPropertyBuilder;
1263 if (pb.Children != null && pb.Children.Count > 0) {
1264 StringBuilder asb = new StringBuilder ();
1265 foreach (string s in pb.Children)
1267 CodeMemberMethod method = builder.method;
1268 CodeAssignStatement assign = new CodeAssignStatement ();
1269 assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
1270 assign.Right = new CodePrimitiveExpression (asb.ToString ());
1271 method.Statements.Add (assign);
1277 if (b is ContentBuilderInternal) {
1278 ContentBuilderInternal cb = (ContentBuilderInternal) b;
1279 CreateControlTree (cb, false, true);
1280 AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
1285 if (b is TemplateBuilder) {
1286 if (templates == null)
1287 templates = new ArrayList ();
1293 if (b is CodeRenderBuilder) {
1294 AddCodeRender (builder, (CodeRenderBuilder) b);
1298 if (b is DataBindingBuilder) {
1299 AddDataBindingLiteral (builder, (DataBindingBuilder) b);
1303 if (b is ControlBuilder) {
1304 ControlBuilder child = (ControlBuilder) b;
1305 CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
1306 AddChildCall (builder, child);
1310 throw new Exception ("???");
1313 FlushText (builder, sb);
1315 if (templates != null) {
1316 foreach (TemplateBuilder b in templates) {
1317 CreateControlTree (b, true, false);
1319 if (b.BindingDirection == BindingDirection.TwoWay) {
1320 string extractMethod = CreateExtractValuesMethod (b);
1321 AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
1325 AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
1331 if (builder.defaultPropertyBuilder != null) {
1332 ControlBuilder b = builder.defaultPropertyBuilder;
1333 CreateControlTree (b, false, true);
1334 AddChildCall (builder, b);
1337 if (builder.HasAspCode) {
1338 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1339 m.TargetObject = thisRef;
1340 m.MethodName = builder.renderMethod.Name;
1342 CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
1343 create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
1344 create.TargetObject = thisRef;
1345 create.MethodName = builder.renderMethod.Name;
1347 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1348 invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
1349 invoke.Parameters.Add (create);
1351 builder.methodStatements.Add (invoke);
1354 if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
1355 builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1358 protected internal override void CreateMethods ()
1360 base.CreateMethods ();
1362 CreateProperties ();
1363 CreateControlTree (parser.RootBuilder, false, false);
1364 CreateFrameworkInitializeMethod ();
1367 void CallBaseFrameworkInitialize (CodeMemberMethod method)
1369 CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
1370 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
1371 method.Statements.Add (invoke);
1374 void CreateFrameworkInitializeMethod ()
1376 CodeMemberMethod method = new CodeMemberMethod ();
1377 method.Name = "FrameworkInitialize";
1378 method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1379 PrependStatementsToFrameworkInitialize (method);
1380 CallBaseFrameworkInitialize (method);
1381 AppendStatementsToFrameworkInitialize (method);
1382 mainClass.Members.Add (method);
1385 protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
1389 protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
1391 if (!parser.EnableViewState) {
1392 CodeAssignStatement stmt = new CodeAssignStatement ();
1393 stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
1394 stmt.Right = new CodePrimitiveExpression (false);
1395 method.Statements.Add (stmt);
1398 CodeMethodReferenceExpression methodExpr;
1399 methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
1400 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
1401 method.Statements.Add (new CodeExpressionStatement (expr));
1404 protected override void AddApplicationAndSessionObjects ()
1406 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
1407 CreateFieldForObject (tag.Type, tag.ObjectID);
1408 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
1411 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
1412 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
1416 protected void ProcessObjectTag (ObjectTagBuilder tag)
1418 string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
1419 CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
1422 void CreateProperties ()
1424 if (!parser.AutoEventWireup) {
1425 CreateAutoEventWireup ();
1427 CreateAutoHandlers ();
1430 CreateApplicationInstance ();
1431 CreateTemplateSourceDirectory ();
1434 void CreateTemplateSourceDirectory ()
1436 CodeMemberProperty prop = new CodeMemberProperty ();
1437 prop.Type = new CodeTypeReference (typeof (string));
1438 prop.Name = "TemplateSourceDirectory";
1439 prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
1441 // if ((this.Parent != null))
1442 // return this.Parent.TemplateSourceDirectory;
1443 CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression ();
1444 parentField.TargetObject = thisRef;
1445 parentField.FieldName = "Parent";
1447 CodeFieldReferenceExpression tsdField = new CodeFieldReferenceExpression ();
1448 tsdField.TargetObject = parentField;
1449 tsdField.FieldName = "TemplateSourceDirectory";
1451 CodeMethodReturnStatement parentRet = new CodeMethodReturnStatement (tsdField);
1452 CodeConditionStatement condStatement = new CodeConditionStatement (
1453 new CodeBinaryOperatorExpression (parentField,
1454 CodeBinaryOperatorType.IdentityInequality,
1455 new CodePrimitiveExpression (null)),
1458 prop.GetStatements.Add (condStatement);
1460 string tsd, bvd = parser.BaseVirtualDir;
1461 int len = bvd.Length;
1462 if (len >= 2 && bvd [0] == '~') {
1464 tsd = bvd.Substring (1);
1466 tsd = '/' + bvd.Substring (1);
1467 } else if (len >= 1 && bvd [0] != '/')
1471 CodePrimitiveExpression expr = new CodePrimitiveExpression (tsd);
1472 prop.GetStatements.Add (new CodeMethodReturnStatement (expr));
1473 mainClass.Members.Add (prop);
1476 void CreateApplicationInstance ()
1478 CodeMemberProperty prop = new CodeMemberProperty ();
1479 Type appType = typeof (HttpApplication);
1480 prop.Type = new CodeTypeReference (appType);
1481 prop.Name = "ApplicationInstance";
1482 prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
1484 CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
1486 propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
1488 CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
1489 prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
1491 if (partialClass != null)
1492 partialClass.Members.Add (prop);
1495 mainClass.Members.Add (prop);
1498 void CreateAutoHandlers ()
1500 // Create AutoHandlers property
1501 CodeMemberProperty prop = new CodeMemberProperty ();
1502 prop.Type = new CodeTypeReference (typeof (int));
1503 prop.Name = "AutoHandlers";
1504 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1506 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
1507 CodeFieldReferenceExpression fldRef ;
1508 fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
1509 ret.Expression = fldRef;
1510 prop.GetStatements.Add (ret);
1511 prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
1514 CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
1515 prop.CustomAttributes.Add (attr);
1518 mainClass.Members.Add (prop);
1520 // Add the __autoHandlers field
1521 CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
1522 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
1523 mainClass.Members.Add (fld);
1526 void CreateAutoEventWireup ()
1528 // The getter returns false
1529 CodeMemberProperty prop = new CodeMemberProperty ();
1530 prop.Type = new CodeTypeReference (typeof (bool));
1531 prop.Name = "SupportAutoEvents";
1532 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1533 prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
1534 mainClass.Members.Add (prop);
1538 protected virtual string HandleUrlProperty (string str, MemberInfo member)
1544 CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
1547 bool wasNullable = false;
1549 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
1550 Type[] types = type.GetGenericArguments();
1551 type = types[0]; // we're interested only in the first type here
1556 if (type == typeof (string)) {
1558 object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
1559 if (urlAttr.Length != 0)
1560 str = HandleUrlProperty (str, member);
1562 return new CodePrimitiveExpression (str);
1565 if (type == typeof (bool)) {
1566 if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
1567 return new CodePrimitiveExpression (true);
1568 else if (InvariantCompareNoCase (str, "false"))
1569 return new CodePrimitiveExpression (false);
1571 else if (wasNullable && InvariantCompareNoCase(str, "null"))
1572 return new CodePrimitiveExpression (null);
1575 throw new ParseException (currentLocation,
1576 "Value '" + str + "' is not a valid boolean.");
1580 return new CodePrimitiveExpression (null);
1582 if (type.IsPrimitive)
1583 return new CodePrimitiveExpression (Convert.ChangeType (str, type, CultureInfo.InvariantCulture));
1585 if (type == typeof (string [])) {
1586 string [] subs = str.Split (',');
1587 CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
1588 expr.CreateType = new CodeTypeReference (typeof (string));
1589 foreach (string v in subs) {
1590 expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
1596 if (type == typeof (Color)){
1597 if (colorConverter == null)
1598 colorConverter = TypeDescriptor.GetConverter (typeof (Color));
1600 if (str.Trim().Length == 0) {
1601 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
1602 return new CodeFieldReferenceExpression (ft, "Empty");
1607 if (str.IndexOf (',') == -1) {
1608 c = (Color) colorConverter.ConvertFromString (str);
1610 int [] argb = new int [4];
1613 string [] parts = str.Split (',');
1614 int length = parts.Length;
1616 throw new Exception ();
1618 int basei = (length == 4) ? 0 : 1;
1619 for (int i = length - 1; i >= 0; i--) {
1620 argb [basei + i] = (int) Byte.Parse (parts [i]);
1622 c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
1624 } catch (Exception e){
1625 // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
1626 // TypeConverter for Color fails to ConvertFromString.
1627 // Hence this hack...
1628 if (InvariantCompareNoCase ("LightGrey", str)) {
1629 c = Color.LightGray;
1631 throw new ParseException (currentLocation,
1632 "Color " + str + " is not a valid color.", e);
1636 if (c.IsKnownColor){
1637 CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
1638 if (c.IsSystemColor)
1639 type = typeof (SystemColors);
1641 expr.TargetObject = new CodeTypeReferenceExpression (type);
1642 expr.FieldName = c.Name;
1645 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1646 m.TargetObject = new CodeTypeReferenceExpression (type);
1647 m.MethodName = "FromArgb";
1648 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1649 invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
1650 invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
1651 invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
1652 invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
1657 TypeConverter converter = TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
1659 if (converter != null && converter.CanConvertFrom (typeof (string))) {
1660 object value = converter.ConvertFromInvariantString (str);
1662 if (converter.CanConvertTo (typeof (InstanceDescriptor))) {
1663 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1664 return GenerateInstance (idesc, true);
1667 CodeExpression exp = GenerateObjectInstance (value, false);
1668 if (exp != null) return exp;
1670 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1671 m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
1672 m.MethodName = "GetConverter";
1673 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1674 CodeTypeReference tref = new CodeTypeReference (type);
1675 invoke.Parameters.Add (new CodeTypeOfExpression (tref));
1677 invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
1678 invoke.Parameters.Add (new CodePrimitiveExpression (str));
1680 return new CodeCastExpression (tref, invoke);
1683 Console.WriteLine ("Unknown type: " + type + " value: " + str);
1685 return new CodePrimitiveExpression (str);
1688 CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
1690 CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
1692 foreach (object ob in idesc.Arguments) {
1693 CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
1694 if (exp == null) return null;
1695 parameters [n++] = exp;
1698 switch (idesc.MemberInfo.MemberType) {
1699 case MemberTypes.Constructor:
1700 CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
1701 return new CodeObjectCreateExpression (tob, parameters);
1703 case MemberTypes.Method:
1704 CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1705 return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
1707 case MemberTypes.Field:
1708 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1709 return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
1711 case MemberTypes.Property:
1712 CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1713 return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
1715 throw new ParseException (currentLocation, "Invalid instance type.");
1718 CodeExpression GenerateObjectInstance (object value, bool throwOnError)
1721 return new CodePrimitiveExpression (null);
1723 Type t = value.GetType();
1724 if (t.IsPrimitive || value is string)
1725 return new CodePrimitiveExpression (value);
1728 Array ar = (Array) value;
1729 CodeExpression[] items = new CodeExpression [ar.Length];
1730 for (int n=0; n<ar.Length; n++) {
1731 CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
1732 if (exp == null) return null;
1735 return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
1738 TypeConverter converter = TypeDescriptor.GetConverter (t);
1739 if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
1740 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1741 return GenerateInstance (idesc, throwOnError);
1744 InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
1745 if (desc != null) return GenerateInstance (desc, throwOnError);
1748 throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
1753 InstanceDescriptor GetDefaultInstanceDescriptor (object value)
1755 if (value is System.Web.UI.WebControls.Unit) {
1756 System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
1757 ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
1758 BindingFlags.Instance | BindingFlags.Public,
1760 new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
1763 return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
1766 if (value is System.Web.UI.WebControls.FontUnit) {
1767 System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
1768 ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
1769 BindingFlags.Instance | BindingFlags.Public,
1771 new Type[] {typeof(System.Web.UI.WebControls.Unit)},
1773 return new InstanceDescriptor (c, new object[] {s.Unit});