2 // System.Web.Compilation.TemplateControlCompiler
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.ComponentModel;
35 using System.Globalization;
36 using System.Reflection;
40 using System.Web.UI.WebControls;
41 using System.Web.Util;
42 using System.ComponentModel.Design.Serialization;
44 using System.Configuration;
45 using System.Collections.Specialized;
46 using System.Collections.Generic;
47 using System.Text.RegularExpressions;
48 using System.Web.Configuration;
51 namespace System.Web.Compilation
53 class TemplateControlCompiler : BaseCompiler
55 static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
56 BindingFlags.Instance | BindingFlags.IgnoreCase;
58 TemplateControlParser parser;
60 ILocation currentLocation;
62 static TypeConverter colorConverter;
64 internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
67 static Regex bindRegex = new Regex (@"Bind\s*\(""(.*?)""\)\s*%>", RegexOptions.Compiled);
70 public TemplateControlCompiler (TemplateControlParser parser)
76 protected void EnsureID (ControlBuilder builder)
78 if (builder.ID == null || builder.ID.Trim () == "")
79 builder.ID = builder.GetNextID (null);
82 void CreateField (ControlBuilder builder, bool check)
84 if (builder == null || builder.ID == null || builder.ControlType == null)
87 if (partialNameOverride [builder.ID] != null)
90 MemberAttributes ma = MemberAttributes.Family;
91 currentLocation = builder.location;
92 if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType, ref ma))
93 return; // The field or property already exists in a base class and is accesible.
95 CodeMemberField field;
96 field = new CodeMemberField (builder.ControlType.FullName, builder.ID);
97 field.Attributes = ma;
99 if (partialClass != null)
100 partialClass.Members.Add (field);
103 mainClass.Members.Add (field);
106 bool CheckBaseFieldOrProperty (string id, Type type, ref MemberAttributes ma)
108 FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);
111 if (fld == null || fld.IsPrivate) {
112 PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
114 MethodInfo setm = prop.GetSetMethod (true);
116 other = prop.PropertyType;
119 other = fld.FieldType;
125 if (!other.IsAssignableFrom (type)) {
127 ma |= MemberAttributes.New;
130 string msg = String.Format ("The base class includes the field '{0}', but its " +
131 "type '{1}' is not compatible with {2}",
133 throw new ParseException (currentLocation, msg);
140 void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr)
142 if (!builder.haveParserVariable) {
143 CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
145 p.Type = new CodeTypeReference (typeof (IParserAccessor));
146 p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
147 builder.methodStatements.Add (p);
148 builder.haveParserVariable = true;
151 CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
152 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
153 invoke.Parameters.Add (expr);
154 builder.methodStatements.Add (invoke);
157 void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
159 string tailname = ((builder is RootBuilder) ? "Tree" : ("_" + builder.ID));
160 CodeMemberMethod method = new CodeMemberMethod ();
161 builder.method = method;
162 builder.methodStatements = method.Statements;
164 method.Name = "__BuildControl" + tailname;
165 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
166 Type type = builder.ControlType;
168 /* in the case this is the __BuildControlTree
169 * method, allow subclasses to insert control
171 if (builder is RootBuilder) {
173 SetCustomAttributes (method);
175 AddStatementsToInitMethod (method);
178 if (builder.HasAspCode) {
179 CodeMemberMethod renderMethod = new CodeMemberMethod ();
180 builder.renderMethod = renderMethod;
181 renderMethod.Name = "__Render" + tailname;
182 renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
183 CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
184 arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
185 arg1.Name = "__output";
186 CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
187 arg2.Type = new CodeTypeReference (typeof (Control));
188 arg2.Name = "parameterContainer";
189 renderMethod.Parameters.Add (arg1);
190 renderMethod.Parameters.Add (arg2);
191 mainClass.Members.Add (renderMethod);
194 if (childrenAsProperties || builder.ControlType == null) {
196 if (builder is RootBuilder)
197 typeString = parser.ClassName;
199 if (builder.ControlType != null && builder.isProperty &&
200 !typeof (ITemplate).IsAssignableFrom (builder.ControlType))
201 typeString = builder.ControlType.FullName;
203 typeString = "System.Web.UI.Control";
206 method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
209 if (typeof (Control).IsAssignableFrom (type))
210 method.ReturnType = new CodeTypeReference (typeof (Control));
212 // _ctrl = new $controlType ($parameters);
214 CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (type);
216 object [] atts = type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true);
217 if (atts != null && atts.Length > 0) {
218 ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
220 newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
221 } else if (builder is DataBindingBuilder) {
222 newExpr.Parameters.Add (new CodePrimitiveExpression (0));
223 newExpr.Parameters.Add (new CodePrimitiveExpression (1));
226 method.Statements.Add (new CodeVariableDeclarationStatement (builder.ControlType, "__ctrl"));
227 CodeAssignStatement assign = new CodeAssignStatement ();
228 assign.Left = ctrlVar;
229 assign.Right = newExpr;
230 method.Statements.Add (assign);
232 // this.$builderID = _ctrl;
234 CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
235 builderID.TargetObject = thisRef;
236 builderID.FieldName = builder.ID;
237 assign = new CodeAssignStatement ();
238 assign.Left = builderID;
239 assign.Right = ctrlVar;
240 method.Statements.Add (assign);
241 if (typeof (UserControl).IsAssignableFrom (type)) {
242 CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
243 mref.TargetObject = builderID;
244 mref.MethodName = "InitializeAsUserControl";
245 CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
246 initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
247 method.Statements.Add (initAsControl);
251 // _ctrl.SkinID = $value
252 // _ctrl.ApplyStyleSheetSkin (this);
254 // the SkinID assignment needs to come
255 // before the call to
256 // ApplyStyleSheetSkin, for obvious
257 // reasons. We skip SkinID in
258 // CreateAssignStatementsFromAttributes
261 if (builder.attribs != null) {
262 string skinid = builder.attribs ["skinid"] as string;
264 CreateAssignStatementFromAttribute (builder, "skinid");
266 if (typeof (WebControl).IsAssignableFrom (type)) {
267 CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
268 if (typeof (Page).IsAssignableFrom (parser.BaseType))
269 applyStyleSheetSkin.Parameters.Add (thisRef);
271 applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
272 method.Statements.Add (applyStyleSheetSkin);
277 if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
278 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (thisRef, "ContentPlaceHolders");
279 CodeMethodInvokeExpression addPlaceholder = new CodeMethodInvokeExpression (prop, "Add");
280 addPlaceholder.Parameters.Add (ctrlVar);
281 method.Statements.Add (addPlaceholder);
284 CodeConditionStatement condStatement;
286 // Add the __Template_* field
287 CodeMemberField fld = new CodeMemberField (typeof (ITemplate), "__Template_" + builder.ID);
288 fld.Attributes = MemberAttributes.Private;
289 mainClass.Members.Add (fld);
291 CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
292 templateID.TargetObject = thisRef;
293 templateID.FieldName = "__Template_" + builder.ID;
295 // if ((this.ContentTemplates != null)) {
296 // this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
299 CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
300 contentTemplates.TargetObject = thisRef;
301 contentTemplates.FieldName = "ContentTemplates";
303 CodeIndexerExpression indexer = new CodeIndexerExpression ();
304 indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
305 indexer.Indices.Add (new CodePrimitiveExpression (builder.ID));
307 assign = new CodeAssignStatement ();
308 assign.Left = templateID;
309 assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);
311 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
312 CodeBinaryOperatorType.IdentityInequality,
313 new CodePrimitiveExpression (null)),
316 method.Statements.Add (condStatement);
318 // if ((this.__Template_mainContent != null)) {
319 // this.__Template_mainContent.InstantiateIn(__ctrl);
321 // and also set things up such that any additional code ends up in:
326 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
327 methodRef.TargetObject = templateID;
328 methodRef.MethodName = "InstantiateIn";
330 CodeMethodInvokeExpression instantiateInInvoke;
331 instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);
333 condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
334 CodeBinaryOperatorType.IdentityInequality,
335 new CodePrimitiveExpression (null)),
336 new CodeExpressionStatement (instantiateInInvoke));
337 method.Statements.Add (condStatement);
339 // this is the bit that causes the following stuff to end up in the else { }
340 builder.methodStatements = condStatement.FalseStatements;
342 // __ctrl.TemplateControl = this;
343 assign = new CodeAssignStatement ();
344 assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
345 assign.Right = thisRef;
347 method.Statements.Add (assign);
352 mainClass.Members.Add (method);
356 void SetCustomAttribute (CodeMemberMethod method, UnknownAttributeDescriptor uad)
358 CodeAssignStatement assign = new CodeAssignStatement ();
359 assign.Left = new CodePropertyReferenceExpression (
360 new CodeArgumentReferenceExpression("__ctrl"),
362 assign.Right = GetExpressionFromString (uad.Value.GetType (), uad.Value.ToString (), uad.Info);
364 method.Statements.Add (assign);
367 void SetCustomAttributes (CodeMemberMethod method)
369 Type baseType = parser.BaseType;
370 if (baseType == null)
373 List <UnknownAttributeDescriptor> attrs = parser.UnknownMainAttributes;
374 if (attrs == null || attrs.Count == 0)
377 foreach (UnknownAttributeDescriptor uad in attrs)
378 SetCustomAttribute (method, uad);
382 protected virtual void AddStatementsToInitMethod (CodeMemberMethod method)
386 void AddLiteralSubObject (ControlBuilder builder, string str)
388 if (!builder.HasAspCode) {
389 CodeObjectCreateExpression expr;
390 expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
391 AddParsedSubObjectStmt (builder, expr);
393 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
394 methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
395 methodRef.MethodName = "Write";
397 CodeMethodInvokeExpression expr;
398 expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
399 builder.renderMethod.Statements.Add (expr);
403 string TrimDB (string value)
405 string str = value.Trim ();
406 str = str.Substring (3);
407 return str.Substring (0, str.Length - 2);
410 string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
412 value = TrimDB (value);
413 CodeMemberMethod method;
414 string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
416 bool need_if = false;
417 value = value.Trim ();
418 if (StrUtils.StartsWith (value, "Bind")) {
419 value = "Eval" + value.Substring (4);
424 method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
426 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
428 // This should be a CodePropertyReferenceExpression for properties... but it works anyway
429 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
432 if (type == typeof (string)) {
433 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
434 CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
435 tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
436 tostring.Parameters.Add (new CodeSnippetExpression (value));
439 CodeSnippetExpression snippet = new CodeSnippetExpression (value);
440 expr = new CodeCastExpression (type, snippet);
443 CodeAssignStatement assign = new CodeAssignStatement (field, expr);
446 CodeExpression page = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Page");
447 CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
448 CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
449 CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
450 method.Statements.Add (ccs);
454 method.Statements.Add (assign);
456 mainClass.Members.Add (method);
460 void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
462 CodeMemberMethod method = builder.method;
463 bool isWritable = IsWritablePropertyOrField (member);
464 if (isDataBound && isWritable) {
465 string dbMethodName = DataBoundProperty (builder, type, var_name, att);
466 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
470 else if (isExpression && isWritable) {
471 AddExpressionAssign (method, member, type, var_name, att);
476 CodeAssignStatement assign = new CodeAssignStatement ();
477 assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
478 currentLocation = builder.location;
479 assign.Right = GetExpressionFromString (type, att, member);
481 method.Statements.Add (assign);
484 bool IsDataBound (string value)
486 if (value == null || value == "")
489 string str = value.Trim ();
490 return (StrUtils.StartsWith (str, "<%#") && StrUtils.EndsWith (str, "%>"));
494 bool IsExpression (string value)
496 if (value == null || value == "")
498 string str = value.Trim ();
499 return (StrUtils.StartsWith (str, "<%$") && StrUtils.EndsWith (str, "%>"));
502 void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
504 string str = value.Trim ();
505 str = str.Substring (3).Trim (); // eats "<%#"
506 if (StrUtils.StartsWith (str, "Bind")) {
507 Match match = bindRegex.Match (str);
509 string bindingName = match.Groups [1].Value;
511 TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
512 if (templateBuilder == null || templateBuilder.BindingDirection == BindingDirection.OneWay)
513 throw new HttpException ("Bind expression not allowed in this context.");
515 string id = builder.attribs ["ID"] as string;
517 throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
519 templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
526 static bool InvariantCompare (string a, string b)
528 return (0 == String.Compare (a, b, false, CultureInfo.InvariantCulture));
532 static bool InvariantCompareNoCase (string a, string b)
534 return (0 == String.Compare (a, b, true, CultureInfo.InvariantCulture));
537 static MemberInfo GetFieldOrProperty (Type type, string name)
539 MemberInfo member = null;
541 member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
548 member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
554 static bool IsWritablePropertyOrField (MemberInfo member)
556 PropertyInfo pi = member as PropertyInfo;
559 FieldInfo fi = member as FieldInfo;
561 return !fi.IsInitOnly;
562 throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
565 bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
566 string attValue, string prefix)
568 int hyphen = id.IndexOf ('-');
569 bool isPropertyInfo = (member is PropertyInfo);
570 bool isDataBound = IsDataBound (attValue);
572 bool isExpression = !isDataBound && IsExpression (attValue);
574 bool isExpression = false;
577 if (isPropertyInfo) {
578 type = ((PropertyInfo) member).PropertyType;
580 type = ((FieldInfo) member).FieldType;
583 if (InvariantCompareNoCase (member.Name, id)) {
586 RegisterBindingInfo (builder, member.Name, ref attValue);
589 if (!IsWritablePropertyOrField (member))
592 AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
599 string prop_field = id.Replace ("-", ".");
600 string [] parts = prop_field.Split (new char [] {'.'});
601 int length = parts.Length;
602 if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
606 MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
607 if (sub_member == null)
610 string new_prefix = prefix + parts [0] + ".";
611 string new_id = id.Substring (hyphen + 1);
612 return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
615 MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
616 if (!(subpf is PropertyInfo))
619 PropertyInfo subprop = (PropertyInfo) subpf;
620 if (subprop.CanWrite == false)
623 bool is_bool = (subprop.PropertyType == typeof (bool));
624 if (!is_bool && attValue == null)
625 return false; // Font-Size -> Font-Size="" as html
627 string val = attValue;
628 if (attValue == null && is_bool)
629 val = "true"; // Font-Bold <=> Font-Bold="true"
631 if (isDataBound) RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
633 AddCodeForPropertyOrField (builder, subprop.PropertyType,
634 prefix + member.Name + "." + subprop.Name,
635 val, subprop, isDataBound, isExpression);
641 void AddExpressionAssign (CodeMemberMethod method, MemberInfo member, Type type, string name, string value)
643 CodeAssignStatement assign = new CodeAssignStatement ();
644 assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
646 // First let's find the correct expression builder
647 string expr = value.Substring (3, value.Length - 5).Trim ();
648 int colon = expr.IndexOf (':');
651 string prefix = expr.Substring (0, colon).Trim ();
653 System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration ("");
656 CompilationSection cs = (CompilationSection)config.GetSection ("system.web/compilation");
659 if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
662 System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
665 string builderType = ceb.Type;
669 t = System.Type.GetType (builderType, true);
670 } catch (Exception e) {
671 throw new HttpException (
672 String.Format ("Failed to load expression builder type `{0}'", builderType), e);
675 if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
676 throw new HttpException (
678 "Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder",
681 System.Web.Compilation.ExpressionBuilder eb = null;
683 ExpressionBuilderContext ctx;
686 eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
687 ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
688 parsedData = eb.ParseExpression (expr.Substring (colon + 1).Trim (), type, ctx);
689 } catch (Exception e) {
690 throw new HttpException (
691 String.Format ("Failed to create an instance of type `{0}'", builderType), e);
693 // FIXME: create and pass an instance of BoundPropertyEntry
694 CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
695 convert.Method = new CodeMethodReferenceExpression (
696 new CodeTypeReferenceExpression (typeof(Convert)),
698 convert.Parameters.Add (eb.GetCodeExpression (null, parsedData, ctx));
699 convert.Parameters.Add (
700 new CodeFieldReferenceExpression (
701 new CodeTypeReferenceExpression ("System.Globalization.CultureInfo"),
703 assign.Right = convert;
705 method.Statements.Add (assign);
708 void AssignPropertyFromResources (CodeMemberMethod method, MemberInfo mi, string attvalue)
710 string resname = String.Format ("{0}.{1}", attvalue, mi.Name);
711 bool isProperty = mi.MemberType == MemberTypes.Property;
712 bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
714 if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
717 Type member_type = null;
719 PropertyInfo pi = mi as PropertyInfo;
720 member_type = pi.PropertyType;
721 } else if (isField) {
722 FieldInfo fi = mi as FieldInfo;
723 member_type = fi.FieldType;
724 } else // should never happen
727 // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
728 string inputFile = parser.InputFile;
729 string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
731 if (StrUtils.StartsWith (inputFile, physPath))
732 inputFile = parser.InputFile.Substring (physPath.Length - 1);
736 object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
740 CodeAssignStatement assign = new CodeAssignStatement ();
741 assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
742 CodeMethodInvokeExpression getlro = new CodeMethodInvokeExpression (
743 new CodeThisReferenceExpression (),
744 "GetLocalResourceObject",
745 new CodeExpression [] { new CodePrimitiveExpression (resname) });
747 CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
748 convert.Method = new CodeMethodReferenceExpression (
749 new CodeTypeReferenceExpression (typeof(System.Convert)),
751 convert.Parameters.Add (getlro);
752 assign.Right = convert;
754 method.Statements.Add (assign);
757 void AssignPropertiesFromResources (CodeMemberMethod method, Type controlType, string attvalue)
759 // Process all public fields and properties of the control. We don't use GetMembers to make the code
761 FieldInfo [] fields = controlType.GetFields (
762 BindingFlags.Instance | BindingFlags.Static |
763 BindingFlags.Public | BindingFlags.FlattenHierarchy);
764 PropertyInfo [] properties = controlType.GetProperties (
765 BindingFlags.Instance | BindingFlags.Static |
766 BindingFlags.Public | BindingFlags.FlattenHierarchy);
768 foreach (FieldInfo fi in fields)
769 AssignPropertyFromResources (method, fi, attvalue);
770 foreach (PropertyInfo pi in properties)
771 AssignPropertyFromResources (method, pi, attvalue);
774 void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
776 if (attvalue == null || attvalue.Length == 0)
779 Type controlType = builder.ControlType;
780 if (controlType == null)
783 AssignPropertiesFromResources (builder.method, controlType, attvalue);
787 void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
789 //"__ctrl.{0} += new {1} (this.{2});"
790 CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
792 CodeDelegateCreateExpression create;
793 create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
795 CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
796 method.Statements.Add (attach);
799 void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
801 EventInfo [] ev_info = null;
802 Type type = builder.ControlType;
804 string attvalue = builder.attribs [id] as string;
805 if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
807 ev_info = type.GetEvents ();
809 string id_as_event = id.Substring (2);
810 foreach (EventInfo ev in ev_info){
811 if (InvariantCompareNoCase (ev.Name, id_as_event)){
812 AddEventAssign (builder.method,
824 if (id.ToLower () == "meta:resourcekey") {
825 AssignPropertiesFromResources (builder, attvalue);
830 int hyphen = id.IndexOf ('-');
833 alt_id = id.Substring (0, hyphen);
835 MemberInfo fop = GetFieldOrProperty (type, alt_id);
837 if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
841 if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
842 throw new ParseException (builder.location, "Unrecognized attribute: " + id);
845 CodeMemberMethod method = builder.method;
846 bool databound = IsDataBound (attvalue);
849 val = attvalue.Substring (3);
850 val = val.Substring (0, val.Length - 2);
851 CreateDBAttributeMethod (builder, id, val);
853 CodeCastExpression cast;
854 CodeMethodReferenceExpression methodExpr;
855 CodeMethodInvokeExpression expr;
857 cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
858 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
859 expr = new CodeMethodInvokeExpression (methodExpr);
860 expr.Parameters.Add (new CodePrimitiveExpression (id));
861 expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
862 method.Statements.Add (expr);
867 protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
870 bool haveMetaKey = false;
872 this.dataBoundAtts = 0;
873 IDictionary atts = builder.attribs;
874 if (atts == null || atts.Count == 0)
877 foreach (string id in atts.Keys) {
878 if (InvariantCompareNoCase (id, "runat"))
882 /* we skip SkinID here as it's assigned in BuildControlTree */
883 if (InvariantCompareNoCase (id, "skinid"))
885 if (InvariantCompareNoCase (id, "meta:resourcekey")) {
890 CreateAssignStatementFromAttribute (builder, id);
895 CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
899 void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
901 if (code == null || code.Trim () == "")
904 string id = builder.GetNextID (null);
905 string dbMethodName = "__DataBind_" + id;
906 CodeMemberMethod method = builder.method;
907 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
909 method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
910 CodeCastExpression cast;
911 CodeMethodReferenceExpression methodExpr;
912 CodeMethodInvokeExpression expr;
914 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
915 cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
916 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
917 expr = new CodeMethodInvokeExpression (methodExpr);
918 expr.Parameters.Add (new CodePrimitiveExpression (attr));
919 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
920 tostring.Method = new CodeMethodReferenceExpression (
921 new CodeTypeReferenceExpression (typeof (Convert)),
923 tostring.Parameters.Add (new CodeSnippetExpression (code));
924 expr.Parameters.Add (tostring);
925 method.Statements.Add (expr);
926 mainClass.Members.Add (method);
929 void AddRenderControl (ControlBuilder builder)
931 CodeIndexerExpression indexer = new CodeIndexerExpression ();
932 indexer.TargetObject = new CodePropertyReferenceExpression (
933 new CodeArgumentReferenceExpression ("parameterContainer"),
936 indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
938 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
939 invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
940 builder.renderMethod.Statements.Add (invoke);
941 builder.renderIndex++;
944 protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
946 if (parent == null || child == null)
948 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
949 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
951 object [] atts = null;
953 if (child.ControlType != null)
954 child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
955 if (atts != null && atts.Length > 0) {
956 PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
957 CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
958 CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
959 build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
960 build.Parameters.Add (new CodePrimitiveExpression (child.ID));
963 build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
966 build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
968 build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
969 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
970 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
971 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
972 build.Parameters.Add (new CodeDelegateCreateExpression (
973 new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
974 thisRef, child.method.Name));
976 parent.methodStatements.Add (build);
977 if (parent.HasAspCode)
978 AddRenderControl (parent);
982 if (child.isProperty || parent.ChildrenAsProperties) {
983 expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
984 parent.methodStatements.Add (expr);
988 parent.methodStatements.Add (expr);
989 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
990 if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
991 AddParsedSubObjectStmt (parent, field);
993 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
994 invoke.Parameters.Add (field);
995 parent.methodStatements.Add (invoke);
998 if (parent.HasAspCode)
999 AddRenderControl (parent);
1002 void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
1004 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1006 CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1007 newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1009 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1010 newCompiled.Parameters.Add (newBuild);
1012 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1013 method.Statements.Add (assign);
1017 void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
1019 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1021 CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1022 newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1024 CodeObjectCreateExpression newExtract = new CodeObjectCreateExpression (typeof (ExtractTemplateValuesMethod));
1025 newExtract.Parameters.Add (new CodeMethodReferenceExpression (thisRef, extractMethodName));
1027 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
1028 newCompiled.Parameters.Add (newBuild);
1029 newCompiled.Parameters.Add (newExtract);
1031 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1032 method.Statements.Add (assign);
1035 string CreateExtractValuesMethod (TemplateBuilder builder)
1037 CodeMemberMethod method = new CodeMemberMethod ();
1038 method.Name = "__ExtractValues_" + builder.ID;
1039 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1040 method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
1042 CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
1043 arg.Type = new CodeTypeReference (typeof (Control));
1044 arg.Name = "__container";
1045 method.Parameters.Add (arg);
1046 mainClass.Members.Add (method);
1048 CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
1049 newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
1050 method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
1051 CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
1053 if (builder.Bindings != null) {
1054 Hashtable hash = new Hashtable ();
1055 foreach (TemplateBinding binding in builder.Bindings) {
1056 CodeConditionStatement sif;
1057 CodeVariableReferenceExpression control;
1058 CodeAssignStatement assign;
1060 if (hash [binding.ControlId] == null) {
1062 CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
1063 method.Statements.Add (dec);
1064 CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
1065 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
1066 invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
1068 assign = new CodeAssignStatement ();
1069 control = new CodeVariableReferenceExpression (binding.ControlId);
1070 assign.Left = control;
1071 assign.Right = new CodeCastExpression (binding.ControlType, invoke);
1072 method.Statements.Add (assign);
1074 sif = new CodeConditionStatement ();
1075 sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
1077 method.Statements.Add (sif);
1079 hash [binding.ControlId] = sif;
1082 sif = (CodeConditionStatement) hash [binding.ControlId];
1083 control = new CodeVariableReferenceExpression (binding.ControlId);
1084 assign = new CodeAssignStatement ();
1085 assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
1086 assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
1087 sif.TrueStatements.Add (assign);
1091 method.Statements.Add (new CodeMethodReturnStatement (tableExp));
1095 void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
1097 CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1098 newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1100 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1101 newCompiled.Parameters.Add (newBuild);
1103 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
1104 invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
1105 invoke.Parameters.Add (newCompiled);
1107 method.Statements.Add (invoke);
1111 void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
1113 if (cr.Code == null || cr.Code.Trim () == "")
1117 CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
1118 parent.renderMethod.Statements.Add (code);
1122 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
1123 expr.Method = new CodeMethodReferenceExpression (
1124 new CodeArgumentReferenceExpression ("__output"),
1127 expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
1128 parent.renderMethod.Statements.Add (expr);
1131 static Type GetContainerType (ControlBuilder builder)
1133 TemplateBuilder tb = builder as TemplateBuilder;
1134 if (tb != null && tb.ContainerType != null)
1135 return tb.ContainerType;
1137 Type type = builder.BindingContainerType;
1139 PropertyInfo prop = type.GetProperty ("Items", noCaseFlags & ~BindingFlags.NonPublic);
1143 Type ptype = prop.PropertyType;
1144 if (!typeof (ICollection).IsAssignableFrom (ptype))
1147 prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
1151 return prop.PropertyType;
1154 CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
1156 CodeMemberMethod method = new CodeMemberMethod ();
1157 method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1159 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
1160 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
1162 CodeTypeReference containerRef = new CodeTypeReference (container);
1163 CodeTypeReference targetRef = new CodeTypeReference (target);
1165 CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
1166 decl.Name = "Container";
1167 decl.Type = containerRef;
1168 method.Statements.Add (decl);
1170 decl = new CodeVariableDeclarationStatement();
1171 decl.Name = "target";
1172 decl.Type = targetRef;
1173 method.Statements.Add (decl);
1175 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1176 CodeAssignStatement assign = new CodeAssignStatement ();
1177 assign.Left = targetExpr;
1178 assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
1179 method.Statements.Add (assign);
1181 assign = new CodeAssignStatement ();
1182 assign.Left = new CodeVariableReferenceExpression ("Container");
1183 assign.Right = new CodeCastExpression (containerRef,
1184 new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
1185 method.Statements.Add (assign);
1190 void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
1192 if (db.Code == null || db.Code.Trim () == "")
1196 CreateField (db, false);
1198 string dbMethodName = "__DataBind_" + db.ID;
1199 // Add the method that builds the DataBoundLiteralControl
1200 InitMethod (db, false, false);
1201 CodeMemberMethod method = db.method;
1202 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
1203 method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1205 // Add the DataBind handler
1206 method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
1208 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1209 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1210 invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
1211 invoke.Parameters.Add (new CodePrimitiveExpression (0));
1213 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
1214 tostring.Method = new CodeMethodReferenceExpression (
1215 new CodeTypeReferenceExpression (typeof (Convert)),
1217 tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
1218 invoke.Parameters.Add (tostring);
1219 method.Statements.Add (invoke);
1221 mainClass.Members.Add (method);
1223 AddChildCall (builder, db);
1226 void FlushText (ControlBuilder builder, StringBuilder sb)
1228 if (sb.Length > 0) {
1229 AddLiteralSubObject (builder, sb.ToString ());
1234 protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
1237 bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
1238 if (!isTemplate && !inTemplate) {
1239 CreateField (builder, true);
1240 } else if (!isTemplate) {
1241 builder.ID = builder.GetNextID (null);
1242 CreateField (builder, false);
1245 InitMethod (builder, isTemplate, childrenAsProperties);
1246 if (!isTemplate || builder.GetType () == typeof (RootBuilder))
1247 CreateAssignStatementsFromAttributes (builder);
1249 if (builder.Children != null && builder.Children.Count > 0) {
1250 ArrayList templates = null;
1252 StringBuilder sb = new StringBuilder ();
1253 foreach (object b in builder.Children) {
1256 sb.Append ((string) b);
1260 FlushText (builder, sb);
1261 if (b is ObjectTagBuilder) {
1262 ProcessObjectTag ((ObjectTagBuilder) b);
1266 StringPropertyBuilder pb = b as StringPropertyBuilder;
1268 if (pb.Children != null && pb.Children.Count > 0) {
1269 StringBuilder asb = new StringBuilder ();
1270 foreach (string s in pb.Children)
1272 CodeMemberMethod method = builder.method;
1273 CodeAssignStatement assign = new CodeAssignStatement ();
1274 assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
1275 assign.Right = new CodePrimitiveExpression (asb.ToString ());
1276 method.Statements.Add (assign);
1282 if (b is ContentBuilderInternal) {
1283 ContentBuilderInternal cb = (ContentBuilderInternal) b;
1284 CreateControlTree (cb, false, true);
1285 AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
1290 if (b is TemplateBuilder) {
1291 if (templates == null)
1292 templates = new ArrayList ();
1298 if (b is CodeRenderBuilder) {
1299 AddCodeRender (builder, (CodeRenderBuilder) b);
1303 if (b is DataBindingBuilder) {
1304 AddDataBindingLiteral (builder, (DataBindingBuilder) b);
1308 if (b is ControlBuilder) {
1309 ControlBuilder child = (ControlBuilder) b;
1310 CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
1311 AddChildCall (builder, child);
1315 throw new Exception ("???");
1318 FlushText (builder, sb);
1320 if (templates != null) {
1321 foreach (TemplateBuilder b in templates) {
1322 CreateControlTree (b, true, false);
1324 if (b.BindingDirection == BindingDirection.TwoWay) {
1325 string extractMethod = CreateExtractValuesMethod (b);
1326 AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
1330 AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
1336 if (builder.defaultPropertyBuilder != null) {
1337 ControlBuilder b = builder.defaultPropertyBuilder;
1338 CreateControlTree (b, false, true);
1339 AddChildCall (builder, b);
1342 if (builder.HasAspCode) {
1343 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1344 m.TargetObject = thisRef;
1345 m.MethodName = builder.renderMethod.Name;
1347 CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
1348 create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
1349 create.TargetObject = thisRef;
1350 create.MethodName = builder.renderMethod.Name;
1352 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1353 invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
1354 invoke.Parameters.Add (create);
1356 builder.methodStatements.Add (invoke);
1359 if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
1360 builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1363 if (builder is RootBuilder)
1364 if (!String.IsNullOrEmpty (parser.MetaResourceKey))
1365 AssignPropertiesFromResources (builder.method, parser.BaseType, parser.MetaResourceKey);
1369 protected internal override void CreateMethods ()
1371 base.CreateMethods ();
1373 CreateProperties ();
1374 CreateControlTree (parser.RootBuilder, false, false);
1375 CreateFrameworkInitializeMethod ();
1378 void CallBaseFrameworkInitialize (CodeMemberMethod method)
1380 CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
1381 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
1382 method.Statements.Add (invoke);
1385 void CreateFrameworkInitializeMethod ()
1387 CodeMemberMethod method = new CodeMemberMethod ();
1388 method.Name = "FrameworkInitialize";
1389 method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1390 PrependStatementsToFrameworkInitialize (method);
1391 CallBaseFrameworkInitialize (method);
1392 AppendStatementsToFrameworkInitialize (method);
1393 mainClass.Members.Add (method);
1396 protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
1400 protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
1402 if (!parser.EnableViewState) {
1403 CodeAssignStatement stmt = new CodeAssignStatement ();
1404 stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
1405 stmt.Right = new CodePrimitiveExpression (false);
1406 method.Statements.Add (stmt);
1409 CodeMethodReferenceExpression methodExpr;
1410 methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
1411 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
1412 method.Statements.Add (new CodeExpressionStatement (expr));
1415 protected override void AddApplicationAndSessionObjects ()
1417 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
1418 CreateFieldForObject (tag.Type, tag.ObjectID);
1419 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
1422 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
1423 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
1427 protected void ProcessObjectTag (ObjectTagBuilder tag)
1429 string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
1430 CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
1433 void CreateProperties ()
1435 if (!parser.AutoEventWireup) {
1436 CreateAutoEventWireup ();
1438 CreateAutoHandlers ();
1441 CreateApplicationInstance ();
1442 CreateTemplateSourceDirectory ();
1445 void CreateTemplateSourceDirectory ()
1447 CodeMemberProperty prop = new CodeMemberProperty ();
1448 prop.Type = new CodeTypeReference (typeof (string));
1449 prop.Name = "TemplateSourceDirectory";
1450 prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
1453 if (!(parser is MasterPageParser)) {
1455 // if ((this.Parent != null))
1456 // return this.Parent.TemplateSourceDirectory;
1457 CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression ();
1458 parentField.TargetObject = thisRef;
1459 parentField.FieldName = "Parent";
1461 CodeFieldReferenceExpression tsdField = new CodeFieldReferenceExpression ();
1462 tsdField.TargetObject = parentField;
1463 tsdField.FieldName = "TemplateSourceDirectory";
1465 CodeMethodReturnStatement parentRet = new CodeMethodReturnStatement (tsdField);
1466 CodeConditionStatement condStatement = new CodeConditionStatement (
1467 new CodeBinaryOperatorExpression (parentField,
1468 CodeBinaryOperatorType.IdentityInequality,
1469 new CodePrimitiveExpression (null)),
1472 prop.GetStatements.Add (condStatement);
1477 string tsd, bvd = parser.BaseVirtualDir;
1478 int len = bvd.Length;
1479 if (len >= 2 && bvd [0] == '~') {
1481 tsd = bvd.Substring (1);
1483 tsd = '/' + bvd.Substring (1);
1484 } else if (len >= 1 && bvd [0] != '/')
1488 CodePrimitiveExpression expr = new CodePrimitiveExpression (tsd);
1489 prop.GetStatements.Add (new CodeMethodReturnStatement (expr));
1490 mainClass.Members.Add (prop);
1493 void CreateApplicationInstance ()
1495 CodeMemberProperty prop = new CodeMemberProperty ();
1496 Type appType = typeof (HttpApplication);
1497 prop.Type = new CodeTypeReference (appType);
1498 prop.Name = "ApplicationInstance";
1499 prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
1501 CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
1503 propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
1505 CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
1506 prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
1508 if (partialClass != null)
1509 partialClass.Members.Add (prop);
1512 mainClass.Members.Add (prop);
1515 void CreateAutoHandlers ()
1517 // Create AutoHandlers property
1518 CodeMemberProperty prop = new CodeMemberProperty ();
1519 prop.Type = new CodeTypeReference (typeof (int));
1520 prop.Name = "AutoHandlers";
1521 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1523 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
1524 CodeFieldReferenceExpression fldRef ;
1525 fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
1526 ret.Expression = fldRef;
1527 prop.GetStatements.Add (ret);
1528 prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
1531 CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
1532 prop.CustomAttributes.Add (attr);
1535 mainClass.Members.Add (prop);
1537 // Add the __autoHandlers field
1538 CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
1539 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
1540 mainClass.Members.Add (fld);
1543 void CreateAutoEventWireup ()
1545 // The getter returns false
1546 CodeMemberProperty prop = new CodeMemberProperty ();
1547 prop.Type = new CodeTypeReference (typeof (bool));
1548 prop.Name = "SupportAutoEvents";
1549 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1550 prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
1551 mainClass.Members.Add (prop);
1555 protected virtual string HandleUrlProperty (string str, MemberInfo member)
1561 CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
1564 bool wasNullable = false;
1566 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
1567 Type[] types = type.GetGenericArguments();
1568 type = types[0]; // we're interested only in the first type here
1573 if (type == typeof (string)) {
1575 object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
1576 if (urlAttr.Length != 0)
1577 str = HandleUrlProperty (str, member);
1579 return new CodePrimitiveExpression (str);
1582 if (type == typeof (bool)) {
1583 if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
1584 return new CodePrimitiveExpression (true);
1585 else if (InvariantCompareNoCase (str, "false"))
1586 return new CodePrimitiveExpression (false);
1588 else if (wasNullable && InvariantCompareNoCase(str, "null"))
1589 return new CodePrimitiveExpression (null);
1592 throw new ParseException (currentLocation,
1593 "Value '" + str + "' is not a valid boolean.");
1597 return new CodePrimitiveExpression (null);
1599 if (type.IsPrimitive)
1600 return new CodePrimitiveExpression (Convert.ChangeType (str, type, CultureInfo.InvariantCulture));
1602 if (type == typeof (string [])) {
1603 string [] subs = str.Split (',');
1604 CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
1605 expr.CreateType = new CodeTypeReference (typeof (string));
1606 foreach (string v in subs) {
1607 expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
1613 if (type == typeof (Color)){
1614 if (colorConverter == null)
1615 colorConverter = TypeDescriptor.GetConverter (typeof (Color));
1617 if (str.Trim().Length == 0) {
1618 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
1619 return new CodeFieldReferenceExpression (ft, "Empty");
1624 if (str.IndexOf (',') == -1) {
1625 c = (Color) colorConverter.ConvertFromString (str);
1627 int [] argb = new int [4];
1630 string [] parts = str.Split (',');
1631 int length = parts.Length;
1633 throw new Exception ();
1635 int basei = (length == 4) ? 0 : 1;
1636 for (int i = length - 1; i >= 0; i--) {
1637 argb [basei + i] = (int) Byte.Parse (parts [i]);
1639 c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
1641 } catch (Exception e){
1642 // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
1643 // TypeConverter for Color fails to ConvertFromString.
1644 // Hence this hack...
1645 if (InvariantCompareNoCase ("LightGrey", str)) {
1646 c = Color.LightGray;
1648 throw new ParseException (currentLocation,
1649 "Color " + str + " is not a valid color.", e);
1653 if (c.IsKnownColor){
1654 CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
1655 if (c.IsSystemColor)
1656 type = typeof (SystemColors);
1658 expr.TargetObject = new CodeTypeReferenceExpression (type);
1659 expr.FieldName = c.Name;
1662 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1663 m.TargetObject = new CodeTypeReferenceExpression (type);
1664 m.MethodName = "FromArgb";
1665 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1666 invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
1667 invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
1668 invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
1669 invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
1674 TypeConverter converter = TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
1676 if (converter != null && converter.CanConvertFrom (typeof (string))) {
1677 object value = converter.ConvertFromInvariantString (str);
1679 if (converter.CanConvertTo (typeof (InstanceDescriptor))) {
1680 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1681 return GenerateInstance (idesc, true);
1684 CodeExpression exp = GenerateObjectInstance (value, false);
1685 if (exp != null) return exp;
1687 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1688 m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
1689 m.MethodName = "GetConverter";
1690 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1691 CodeTypeReference tref = new CodeTypeReference (type);
1692 invoke.Parameters.Add (new CodeTypeOfExpression (tref));
1694 invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
1695 invoke.Parameters.Add (new CodePrimitiveExpression (str));
1697 return new CodeCastExpression (tref, invoke);
1700 Console.WriteLine ("Unknown type: " + type + " value: " + str);
1702 return new CodePrimitiveExpression (str);
1705 CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
1707 CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
1709 foreach (object ob in idesc.Arguments) {
1710 CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
1711 if (exp == null) return null;
1712 parameters [n++] = exp;
1715 switch (idesc.MemberInfo.MemberType) {
1716 case MemberTypes.Constructor:
1717 CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
1718 return new CodeObjectCreateExpression (tob, parameters);
1720 case MemberTypes.Method:
1721 CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1722 return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
1724 case MemberTypes.Field:
1725 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1726 return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
1728 case MemberTypes.Property:
1729 CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1730 return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
1732 throw new ParseException (currentLocation, "Invalid instance type.");
1735 CodeExpression GenerateObjectInstance (object value, bool throwOnError)
1738 return new CodePrimitiveExpression (null);
1740 Type t = value.GetType();
1741 if (t.IsPrimitive || value is string)
1742 return new CodePrimitiveExpression (value);
1745 Array ar = (Array) value;
1746 CodeExpression[] items = new CodeExpression [ar.Length];
1747 for (int n=0; n<ar.Length; n++) {
1748 CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
1749 if (exp == null) return null;
1752 return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
1755 TypeConverter converter = TypeDescriptor.GetConverter (t);
1756 if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
1757 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1758 return GenerateInstance (idesc, throwOnError);
1761 InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
1762 if (desc != null) return GenerateInstance (desc, throwOnError);
1765 throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
1770 InstanceDescriptor GetDefaultInstanceDescriptor (object value)
1772 if (value is System.Web.UI.WebControls.Unit) {
1773 System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
1774 ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
1775 BindingFlags.Instance | BindingFlags.Public,
1777 new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
1780 return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
1783 if (value is System.Web.UI.WebControls.FontUnit) {
1784 System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
1786 Type cParamType = null;
1787 object cParam = null;
1790 case FontSize.AsUnit:
1791 case FontSize.NotSet:
1792 cParamType = typeof (System.Web.UI.WebControls.Unit);
1797 cParamType = typeof (string);
1798 cParam = s.Type.ToString ();
1802 ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
1803 BindingFlags.Instance | BindingFlags.Public,
1805 new Type[] {cParamType},
1808 return new InstanceDescriptor (c, new object[] {cParam});