2 // System.Web.Compilation.TemplateControlCompiler
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.ComponentModel;
35 using System.Globalization;
36 using System.Reflection;
40 using System.Web.UI.WebControls;
41 using System.Web.Util;
42 using System.ComponentModel.Design.Serialization;
44 using System.Configuration;
45 using System.Collections.Specialized;
46 using System.Collections.Generic;
47 using System.Text.RegularExpressions;
48 using System.Web.Configuration;
51 namespace System.Web.Compilation
53 class TemplateControlCompiler : BaseCompiler
55 static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
56 BindingFlags.Instance | BindingFlags.IgnoreCase;
58 TemplateControlParser parser;
60 ILocation currentLocation;
62 static TypeConverter colorConverter;
64 internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
67 static Regex bindRegex = new Regex (@"Bind\s*\(""(.*?)""\)\s*%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
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", true)) {
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 (thisRef, "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", true)) {
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);
694 BoundPropertyEntry bpe = CreateBoundPropertyEntry (member as PropertyInfo, prefix, expr);
695 assign.Right = eb.GetCodeExpression (bpe, parsedData, ctx);
697 method.Statements.Add (assign);
700 BoundPropertyEntry CreateBoundPropertyEntry (PropertyInfo pi, string prefix, string expr)
705 BoundPropertyEntry ret = new BoundPropertyEntry ();
706 ret.Expression = expr;
707 ret.ExpressionPrefix = prefix;
708 ret.Generated = false;
710 ret.PropertyInfo = pi;
711 ret.Type = pi.PropertyType;
716 void AssignPropertyFromResources (CodeMemberMethod method, MemberInfo mi, string attvalue)
718 bool isProperty = mi.MemberType == MemberTypes.Property;
719 bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
721 if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
724 string memberName = mi.Name;
725 string resname = String.Format ("{0}.{1}", attvalue, memberName);
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 Type member_type = null;
742 member_type = ((PropertyInfo)mi).PropertyType;
744 member_type = ((FieldInfo)mi).FieldType;
746 return; // an "impossible" case
748 Type declaringType = mi.DeclaringType;
749 TypeConverter converter = TypeDescriptor.GetProperties (declaringType) [memberName].Converter;
750 CodeAssignStatement assign = new CodeAssignStatement ();
752 assign.Left = new CodePropertyReferenceExpression (ctrlVar, memberName);
753 assign.Right = ResourceExpressionBuilder.CreateGetLocalResourceObject (mi, resname);
755 method.Statements.Add (assign);
758 void AssignPropertiesFromResources (CodeMemberMethod method, Type controlType, string attvalue)
760 // Process all public fields and properties of the control. We don't use GetMembers to make the code
762 FieldInfo [] fields = controlType.GetFields (
763 BindingFlags.Instance | BindingFlags.Static |
764 BindingFlags.Public | BindingFlags.FlattenHierarchy);
765 PropertyInfo [] properties = controlType.GetProperties (
766 BindingFlags.Instance | BindingFlags.Static |
767 BindingFlags.Public | BindingFlags.FlattenHierarchy);
769 foreach (FieldInfo fi in fields)
770 AssignPropertyFromResources (method, fi, attvalue);
771 foreach (PropertyInfo pi in properties)
772 AssignPropertyFromResources (method, pi, attvalue);
775 void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
777 if (attvalue == null || attvalue.Length == 0)
780 Type controlType = builder.ControlType;
781 if (controlType == null)
784 AssignPropertiesFromResources (builder.method, controlType, attvalue);
788 void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
790 //"__ctrl.{0} += new {1} (this.{2});"
791 CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
793 CodeDelegateCreateExpression create;
794 create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
796 CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
797 method.Statements.Add (attach);
800 void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
802 EventInfo [] ev_info = null;
803 Type type = builder.ControlType;
805 string attvalue = builder.attribs [id] as string;
806 if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
808 ev_info = type.GetEvents ();
810 string id_as_event = id.Substring (2);
811 foreach (EventInfo ev in ev_info){
812 if (InvariantCompareNoCase (ev.Name, id_as_event)){
813 AddEventAssign (builder.method,
825 if (id.ToLower () == "meta:resourcekey") {
826 AssignPropertiesFromResources (builder, attvalue);
831 int hyphen = id.IndexOf ('-');
834 alt_id = id.Substring (0, hyphen);
836 MemberInfo fop = GetFieldOrProperty (type, alt_id);
838 if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
842 if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
843 throw new ParseException (builder.location, "Unrecognized attribute: " + id);
846 CodeMemberMethod method = builder.method;
847 bool databound = IsDataBound (attvalue);
850 val = attvalue.Substring (3);
851 val = val.Substring (0, val.Length - 2);
852 CreateDBAttributeMethod (builder, id, val);
854 CodeCastExpression cast;
855 CodeMethodReferenceExpression methodExpr;
856 CodeMethodInvokeExpression expr;
858 cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
859 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
860 expr = new CodeMethodInvokeExpression (methodExpr);
861 expr.Parameters.Add (new CodePrimitiveExpression (id));
862 expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
863 method.Statements.Add (expr);
868 protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
871 bool haveMetaKey = false;
873 this.dataBoundAtts = 0;
874 IDictionary atts = builder.attribs;
875 if (atts == null || atts.Count == 0)
878 foreach (string id in atts.Keys) {
879 if (InvariantCompareNoCase (id, "runat"))
883 /* we skip SkinID here as it's assigned in BuildControlTree */
884 if (InvariantCompareNoCase (id, "skinid"))
886 if (InvariantCompareNoCase (id, "meta:resourcekey")) {
891 CreateAssignStatementFromAttribute (builder, id);
896 CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
900 void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
902 if (code == null || code.Trim () == "")
905 string id = builder.GetNextID (null);
906 string dbMethodName = "__DataBind_" + id;
907 CodeMemberMethod method = builder.method;
908 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
910 method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
911 CodeCastExpression cast;
912 CodeMethodReferenceExpression methodExpr;
913 CodeMethodInvokeExpression expr;
915 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
916 cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
917 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
918 expr = new CodeMethodInvokeExpression (methodExpr);
919 expr.Parameters.Add (new CodePrimitiveExpression (attr));
920 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
921 tostring.Method = new CodeMethodReferenceExpression (
922 new CodeTypeReferenceExpression (typeof (Convert)),
924 tostring.Parameters.Add (new CodeSnippetExpression (code));
925 expr.Parameters.Add (tostring);
926 method.Statements.Add (expr);
927 mainClass.Members.Add (method);
930 void AddRenderControl (ControlBuilder builder)
932 CodeIndexerExpression indexer = new CodeIndexerExpression ();
933 indexer.TargetObject = new CodePropertyReferenceExpression (
934 new CodeArgumentReferenceExpression ("parameterContainer"),
937 indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
939 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
940 invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
941 builder.renderMethod.Statements.Add (invoke);
942 builder.renderIndex++;
945 protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
947 if (parent == null || child == null)
949 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
950 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
952 object [] atts = null;
954 if (child.ControlType != null)
955 child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
956 if (atts != null && atts.Length > 0) {
957 PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
958 CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
959 CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
960 build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
961 build.Parameters.Add (new CodePrimitiveExpression (child.ID));
964 build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
967 build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
969 build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
970 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
971 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
972 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
973 build.Parameters.Add (new CodeDelegateCreateExpression (
974 new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
975 thisRef, child.method.Name));
977 parent.methodStatements.Add (build);
978 if (parent.HasAspCode)
979 AddRenderControl (parent);
983 if (child.isProperty || parent.ChildrenAsProperties) {
984 expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
985 parent.methodStatements.Add (expr);
989 parent.methodStatements.Add (expr);
990 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
991 if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
992 AddParsedSubObjectStmt (parent, field);
994 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
995 invoke.Parameters.Add (field);
996 parent.methodStatements.Add (invoke);
999 if (parent.HasAspCode)
1000 AddRenderControl (parent);
1003 void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
1005 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1007 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1008 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1010 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1011 newCompiled.Parameters.Add (newBuild);
1013 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1014 method.Statements.Add (assign);
1018 void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
1020 CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1022 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1023 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1025 CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
1026 new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);
1028 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
1029 newCompiled.Parameters.Add (newBuild);
1030 newCompiled.Parameters.Add (newExtract);
1032 CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1033 method.Statements.Add (assign);
1036 string CreateExtractValuesMethod (TemplateBuilder builder)
1038 CodeMemberMethod method = new CodeMemberMethod ();
1039 method.Name = "__ExtractValues_" + builder.ID;
1040 method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1041 method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
1043 CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
1044 arg.Type = new CodeTypeReference (typeof (Control));
1045 arg.Name = "__container";
1046 method.Parameters.Add (arg);
1047 mainClass.Members.Add (method);
1049 CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
1050 newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
1051 method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
1052 CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
1054 if (builder.Bindings != null) {
1055 Hashtable hash = new Hashtable ();
1056 foreach (TemplateBinding binding in builder.Bindings) {
1057 CodeConditionStatement sif;
1058 CodeVariableReferenceExpression control;
1059 CodeAssignStatement assign;
1061 if (hash [binding.ControlId] == null) {
1063 CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
1064 method.Statements.Add (dec);
1065 CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
1066 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
1067 invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
1069 assign = new CodeAssignStatement ();
1070 control = new CodeVariableReferenceExpression (binding.ControlId);
1071 assign.Left = control;
1072 assign.Right = new CodeCastExpression (binding.ControlType, invoke);
1073 method.Statements.Add (assign);
1075 sif = new CodeConditionStatement ();
1076 sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
1078 method.Statements.Add (sif);
1080 hash [binding.ControlId] = sif;
1083 sif = (CodeConditionStatement) hash [binding.ControlId];
1084 control = new CodeVariableReferenceExpression (binding.ControlId);
1085 assign = new CodeAssignStatement ();
1086 assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
1087 assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
1088 sif.TrueStatements.Add (assign);
1092 method.Statements.Add (new CodeMethodReturnStatement (tableExp));
1096 void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
1098 CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
1099 new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);
1101 CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1102 newCompiled.Parameters.Add (newBuild);
1104 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
1105 invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
1106 invoke.Parameters.Add (newCompiled);
1108 method.Statements.Add (invoke);
1112 void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
1114 if (cr.Code == null || cr.Code.Trim () == "")
1118 CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
1119 parent.renderMethod.Statements.Add (code);
1123 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
1124 expr.Method = new CodeMethodReferenceExpression (
1125 new CodeArgumentReferenceExpression ("__output"),
1128 expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
1129 parent.renderMethod.Statements.Add (expr);
1132 static Type GetContainerType (ControlBuilder builder)
1134 TemplateBuilder tb = builder as TemplateBuilder;
1135 if (tb != null && tb.ContainerType != null)
1136 return tb.ContainerType;
1138 Type type = builder.BindingContainerType;
1140 PropertyInfo prop = type.GetProperty ("Items", noCaseFlags & ~BindingFlags.NonPublic);
1144 Type ptype = prop.PropertyType;
1145 if (!typeof (ICollection).IsAssignableFrom (ptype))
1148 prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
1152 return prop.PropertyType;
1155 CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
1157 CodeMemberMethod method = new CodeMemberMethod ();
1158 method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1160 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
1161 method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
1163 CodeTypeReference containerRef = new CodeTypeReference (container);
1164 CodeTypeReference targetRef = new CodeTypeReference (target);
1166 CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
1167 decl.Name = "Container";
1168 decl.Type = containerRef;
1169 method.Statements.Add (decl);
1171 decl = new CodeVariableDeclarationStatement();
1172 decl.Name = "target";
1173 decl.Type = targetRef;
1174 method.Statements.Add (decl);
1176 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1177 CodeAssignStatement assign = new CodeAssignStatement ();
1178 assign.Left = targetExpr;
1179 assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
1180 method.Statements.Add (assign);
1182 assign = new CodeAssignStatement ();
1183 assign.Left = new CodeVariableReferenceExpression ("Container");
1184 assign.Right = new CodeCastExpression (containerRef,
1185 new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
1186 method.Statements.Add (assign);
1191 void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
1193 if (db.Code == null || db.Code.Trim () == "")
1197 CreateField (db, false);
1199 string dbMethodName = "__DataBind_" + db.ID;
1200 // Add the method that builds the DataBoundLiteralControl
1201 InitMethod (db, false, false);
1202 CodeMemberMethod method = db.method;
1203 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
1204 method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1206 // Add the DataBind handler
1207 method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
1209 CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1210 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1211 invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
1212 invoke.Parameters.Add (new CodePrimitiveExpression (0));
1214 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
1215 tostring.Method = new CodeMethodReferenceExpression (
1216 new CodeTypeReferenceExpression (typeof (Convert)),
1218 tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
1219 invoke.Parameters.Add (tostring);
1220 method.Statements.Add (invoke);
1222 mainClass.Members.Add (method);
1224 AddChildCall (builder, db);
1227 void FlushText (ControlBuilder builder, StringBuilder sb)
1229 if (sb.Length > 0) {
1230 AddLiteralSubObject (builder, sb.ToString ());
1235 protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
1238 bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
1239 if (!isTemplate && !inTemplate) {
1240 CreateField (builder, true);
1241 } else if (!isTemplate) {
1242 builder.ID = builder.GetNextID (null);
1243 CreateField (builder, false);
1246 InitMethod (builder, isTemplate, childrenAsProperties);
1247 if (!isTemplate || builder.GetType () == typeof (RootBuilder))
1248 CreateAssignStatementsFromAttributes (builder);
1250 if (builder.Children != null && builder.Children.Count > 0) {
1251 ArrayList templates = null;
1253 StringBuilder sb = new StringBuilder ();
1254 foreach (object b in builder.Children) {
1257 sb.Append ((string) b);
1261 FlushText (builder, sb);
1262 if (b is ObjectTagBuilder) {
1263 ProcessObjectTag ((ObjectTagBuilder) b);
1267 StringPropertyBuilder pb = b as StringPropertyBuilder;
1269 if (pb.Children != null && pb.Children.Count > 0) {
1270 StringBuilder asb = new StringBuilder ();
1271 foreach (string s in pb.Children)
1273 CodeMemberMethod method = builder.method;
1274 CodeAssignStatement assign = new CodeAssignStatement ();
1275 assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
1276 assign.Right = new CodePrimitiveExpression (asb.ToString ());
1277 method.Statements.Add (assign);
1283 if (b is ContentBuilderInternal) {
1284 ContentBuilderInternal cb = (ContentBuilderInternal) b;
1285 CreateControlTree (cb, false, true);
1286 AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
1291 if (b is TemplateBuilder) {
1292 if (templates == null)
1293 templates = new ArrayList ();
1299 if (b is CodeRenderBuilder) {
1300 AddCodeRender (builder, (CodeRenderBuilder) b);
1304 if (b is DataBindingBuilder) {
1305 AddDataBindingLiteral (builder, (DataBindingBuilder) b);
1309 if (b is ControlBuilder) {
1310 ControlBuilder child = (ControlBuilder) b;
1311 CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
1312 AddChildCall (builder, child);
1316 throw new Exception ("???");
1319 FlushText (builder, sb);
1321 if (templates != null) {
1322 foreach (TemplateBuilder b in templates) {
1323 CreateControlTree (b, true, false);
1325 if (b.BindingDirection == BindingDirection.TwoWay) {
1326 string extractMethod = CreateExtractValuesMethod (b);
1327 AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
1331 AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
1337 if (builder.defaultPropertyBuilder != null) {
1338 ControlBuilder b = builder.defaultPropertyBuilder;
1339 CreateControlTree (b, false, true);
1340 AddChildCall (builder, b);
1343 if (builder.HasAspCode) {
1344 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1345 m.TargetObject = thisRef;
1346 m.MethodName = builder.renderMethod.Name;
1348 CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
1349 create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
1350 create.TargetObject = thisRef;
1351 create.MethodName = builder.renderMethod.Name;
1353 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1354 invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
1355 invoke.Parameters.Add (create);
1357 builder.methodStatements.Add (invoke);
1360 if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
1361 builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1364 if (builder is RootBuilder)
1365 if (!String.IsNullOrEmpty (parser.MetaResourceKey))
1366 AssignPropertiesFromResources (builder.method, parser.BaseType, parser.MetaResourceKey);
1370 protected internal override void CreateMethods ()
1372 base.CreateMethods ();
1374 CreateProperties ();
1375 CreateControlTree (parser.RootBuilder, false, false);
1376 CreateFrameworkInitializeMethod ();
1379 void CallBaseFrameworkInitialize (CodeMemberMethod method)
1381 CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
1382 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
1383 method.Statements.Add (invoke);
1386 void CreateFrameworkInitializeMethod ()
1388 CodeMemberMethod method = new CodeMemberMethod ();
1389 method.Name = "FrameworkInitialize";
1390 method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1391 PrependStatementsToFrameworkInitialize (method);
1392 CallBaseFrameworkInitialize (method);
1393 AppendStatementsToFrameworkInitialize (method);
1394 mainClass.Members.Add (method);
1397 protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
1401 protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
1403 if (!parser.EnableViewState) {
1404 CodeAssignStatement stmt = new CodeAssignStatement ();
1405 stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
1406 stmt.Right = new CodePrimitiveExpression (false);
1407 method.Statements.Add (stmt);
1410 CodeMethodReferenceExpression methodExpr;
1411 methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
1412 CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
1413 method.Statements.Add (new CodeExpressionStatement (expr));
1416 protected override void AddApplicationAndSessionObjects ()
1418 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
1419 CreateFieldForObject (tag.Type, tag.ObjectID);
1420 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
1423 foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
1424 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
1428 protected void ProcessObjectTag (ObjectTagBuilder tag)
1430 string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
1431 CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
1434 void CreateProperties ()
1436 if (!parser.AutoEventWireup) {
1437 CreateAutoEventWireup ();
1439 CreateAutoHandlers ();
1442 CreateApplicationInstance ();
1443 CreateTemplateSourceDirectory ();
1446 void CreateTemplateSourceDirectory ()
1448 CodeMemberProperty prop = new CodeMemberProperty ();
1449 prop.Type = new CodeTypeReference (typeof (string));
1450 prop.Name = "TemplateSourceDirectory";
1451 prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
1454 if (!(parser is MasterPageParser)) {
1456 // if ((this.TemplateControl != null))
1457 // return this.TemplateControl.TemplateSourceDirectory;
1458 CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression ();
1459 parentField.TargetObject = thisRef;
1461 parentField.FieldName = "TemplateControl";
1463 parentField.FieldName = "Parent";
1465 CodeFieldReferenceExpression tsdField = new CodeFieldReferenceExpression ();
1466 tsdField.TargetObject = parentField;
1467 tsdField.FieldName = "TemplateSourceDirectory";
1469 CodeMethodReturnStatement parentRet = new CodeMethodReturnStatement (tsdField);
1470 CodeConditionStatement condStatement = new CodeConditionStatement (
1471 new CodeBinaryOperatorExpression (parentField,
1472 CodeBinaryOperatorType.IdentityInequality,
1473 new CodePrimitiveExpression (null)),
1476 prop.GetStatements.Add (condStatement);
1481 string tsd, bvd = parser.BaseVirtualDir;
1482 int len = bvd.Length;
1483 if (len >= 2 && bvd [0] == '~') {
1485 tsd = bvd.Substring (1);
1487 tsd = '/' + bvd.Substring (1);
1488 } else if (len >= 1 && bvd [0] != '/')
1492 CodePrimitiveExpression expr = new CodePrimitiveExpression (tsd);
1493 prop.GetStatements.Add (new CodeMethodReturnStatement (expr));
1494 mainClass.Members.Add (prop);
1497 void CreateApplicationInstance ()
1499 CodeMemberProperty prop = new CodeMemberProperty ();
1500 Type appType = typeof (HttpApplication);
1501 prop.Type = new CodeTypeReference (appType);
1502 prop.Name = "ApplicationInstance";
1503 prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
1505 CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
1507 propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
1509 CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
1510 prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
1512 if (partialClass != null)
1513 partialClass.Members.Add (prop);
1516 mainClass.Members.Add (prop);
1519 void CreateAutoHandlers ()
1521 // Create AutoHandlers property
1522 CodeMemberProperty prop = new CodeMemberProperty ();
1523 prop.Type = new CodeTypeReference (typeof (int));
1524 prop.Name = "AutoHandlers";
1525 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1527 CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
1528 CodeFieldReferenceExpression fldRef ;
1529 fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
1530 ret.Expression = fldRef;
1531 prop.GetStatements.Add (ret);
1532 prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
1535 CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
1536 prop.CustomAttributes.Add (attr);
1539 mainClass.Members.Add (prop);
1541 // Add the __autoHandlers field
1542 CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
1543 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
1544 mainClass.Members.Add (fld);
1547 void CreateAutoEventWireup ()
1549 // The getter returns false
1550 CodeMemberProperty prop = new CodeMemberProperty ();
1551 prop.Type = new CodeTypeReference (typeof (bool));
1552 prop.Name = "SupportAutoEvents";
1553 prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1554 prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
1555 mainClass.Members.Add (prop);
1559 protected virtual string HandleUrlProperty (string str, MemberInfo member)
1565 CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
1568 bool wasNullable = false;
1570 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
1571 Type[] types = type.GetGenericArguments();
1572 type = types[0]; // we're interested only in the first type here
1577 if (type == typeof (string)) {
1579 object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
1580 if (urlAttr.Length != 0)
1581 str = HandleUrlProperty (str, member);
1583 return new CodePrimitiveExpression (str);
1586 if (type == typeof (bool)) {
1587 if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
1588 return new CodePrimitiveExpression (true);
1589 else if (InvariantCompareNoCase (str, "false"))
1590 return new CodePrimitiveExpression (false);
1592 else if (wasNullable && InvariantCompareNoCase(str, "null"))
1593 return new CodePrimitiveExpression (null);
1596 throw new ParseException (currentLocation,
1597 "Value '" + str + "' is not a valid boolean.");
1601 return new CodePrimitiveExpression (null);
1603 if (type.IsPrimitive)
1604 return new CodePrimitiveExpression (Convert.ChangeType (str, type, CultureInfo.InvariantCulture));
1606 if (type == typeof (string [])) {
1607 string [] subs = str.Split (',');
1608 CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
1609 expr.CreateType = new CodeTypeReference (typeof (string));
1610 foreach (string v in subs) {
1611 expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
1617 if (type == typeof (Color)){
1618 if (colorConverter == null)
1619 colorConverter = TypeDescriptor.GetConverter (typeof (Color));
1621 if (str.Trim().Length == 0) {
1622 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
1623 return new CodeFieldReferenceExpression (ft, "Empty");
1628 if (str.IndexOf (',') == -1) {
1629 c = (Color) colorConverter.ConvertFromString (str);
1631 int [] argb = new int [4];
1634 string [] parts = str.Split (',');
1635 int length = parts.Length;
1637 throw new Exception ();
1639 int basei = (length == 4) ? 0 : 1;
1640 for (int i = length - 1; i >= 0; i--) {
1641 argb [basei + i] = (int) Byte.Parse (parts [i]);
1643 c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
1645 } catch (Exception e){
1646 // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
1647 // TypeConverter for Color fails to ConvertFromString.
1648 // Hence this hack...
1649 if (InvariantCompareNoCase ("LightGrey", str)) {
1650 c = Color.LightGray;
1652 throw new ParseException (currentLocation,
1653 "Color " + str + " is not a valid color.", e);
1657 if (c.IsKnownColor){
1658 CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
1659 if (c.IsSystemColor)
1660 type = typeof (SystemColors);
1662 expr.TargetObject = new CodeTypeReferenceExpression (type);
1663 expr.FieldName = c.Name;
1666 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1667 m.TargetObject = new CodeTypeReferenceExpression (type);
1668 m.MethodName = "FromArgb";
1669 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1670 invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
1671 invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
1672 invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
1673 invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
1678 TypeConverter converter = TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
1680 if (converter != null && converter.CanConvertFrom (typeof (string))) {
1681 object value = converter.ConvertFromInvariantString (str);
1683 if (converter.CanConvertTo (typeof (InstanceDescriptor))) {
1684 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1685 return GenerateInstance (idesc, true);
1688 CodeExpression exp = GenerateObjectInstance (value, false);
1689 if (exp != null) return exp;
1691 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1692 m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
1693 m.MethodName = "GetConverter";
1694 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1695 CodeTypeReference tref = new CodeTypeReference (type);
1696 invoke.Parameters.Add (new CodeTypeOfExpression (tref));
1698 invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
1699 invoke.Parameters.Add (new CodePrimitiveExpression (str));
1701 return new CodeCastExpression (tref, invoke);
1704 Console.WriteLine ("Unknown type: " + type + " value: " + str);
1706 return new CodePrimitiveExpression (str);
1709 CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
1711 CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
1713 foreach (object ob in idesc.Arguments) {
1714 CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
1715 if (exp == null) return null;
1716 parameters [n++] = exp;
1719 switch (idesc.MemberInfo.MemberType) {
1720 case MemberTypes.Constructor:
1721 CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
1722 return new CodeObjectCreateExpression (tob, parameters);
1724 case MemberTypes.Method:
1725 CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1726 return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
1728 case MemberTypes.Field:
1729 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1730 return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
1732 case MemberTypes.Property:
1733 CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1734 return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
1736 throw new ParseException (currentLocation, "Invalid instance type.");
1739 CodeExpression GenerateObjectInstance (object value, bool throwOnError)
1742 return new CodePrimitiveExpression (null);
1744 Type t = value.GetType();
1745 if (t.IsPrimitive || value is string)
1746 return new CodePrimitiveExpression (value);
1749 Array ar = (Array) value;
1750 CodeExpression[] items = new CodeExpression [ar.Length];
1751 for (int n=0; n<ar.Length; n++) {
1752 CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
1753 if (exp == null) return null;
1756 return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
1759 TypeConverter converter = TypeDescriptor.GetConverter (t);
1760 if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
1761 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1762 return GenerateInstance (idesc, throwOnError);
1765 InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
1766 if (desc != null) return GenerateInstance (desc, throwOnError);
1769 throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
1774 InstanceDescriptor GetDefaultInstanceDescriptor (object value)
1776 if (value is System.Web.UI.WebControls.Unit) {
1777 System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
1778 ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
1779 BindingFlags.Instance | BindingFlags.Public,
1781 new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
1784 return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
1787 if (value is System.Web.UI.WebControls.FontUnit) {
1788 System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
1790 Type cParamType = null;
1791 object cParam = null;
1794 case FontSize.AsUnit:
1795 case FontSize.NotSet:
1796 cParamType = typeof (System.Web.UI.WebControls.Unit);
1801 cParamType = typeof (string);
1802 cParam = s.Type.ToString ();
1806 ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
1807 BindingFlags.Instance | BindingFlags.Public,
1809 new Type[] {cParamType},
1812 return new InstanceDescriptor (c, new object[] {cParam});