Mark tests as not working under TARGET_JVM
[mono.git] / mcs / class / System.Web / System.Web.Compilation / TemplateControlCompiler.cs
1 //
2 // System.Web.Compilation.TemplateControlCompiler
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
8 //
9
10 //
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:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
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.
29 //
30 using System;
31 using System.CodeDom;
32 using System.Collections;
33 using System.ComponentModel;
34 using System.Drawing;
35 using System.Globalization;
36 using System.Reflection;
37 using System.Text;
38 using System.Web;
39 using System.Web.UI;
40 using System.Web.UI.WebControls;
41 using System.Web.Util;
42 using System.ComponentModel.Design.Serialization;
43 #if NET_2_0
44 using System.Configuration;
45 using System.Collections.Specialized;
46 using System.Text.RegularExpressions;
47 using System.Web.Configuration;
48 #endif
49
50 namespace System.Web.Compilation
51 {
52         class TemplateControlCompiler : BaseCompiler
53         {
54                 static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
55                                                   BindingFlags.Instance | BindingFlags.IgnoreCase;
56
57                 TemplateControlParser parser;
58                 int dataBoundAtts;
59                 ILocation currentLocation;
60
61                 static TypeConverter colorConverter;
62
63                 internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
64                 
65 #if NET_2_0
66                 static Regex bindRegex = new Regex (@"Bind\s*\(""(.*?)""\)\s*%>", RegexOptions.Compiled);
67 #endif
68
69                 public TemplateControlCompiler (TemplateControlParser parser)
70                         : base (parser)
71                 {
72                         this.parser = parser;
73                 }
74
75                 protected void EnsureID (ControlBuilder builder)
76                 {
77                         if (builder.ID == null || builder.ID.Trim () == "")
78                                 builder.ID = builder.GetNextID (null);
79                 }
80
81                 void CreateField (ControlBuilder builder, bool check)
82                 {
83                         if (builder == null || builder.ID == null || builder.ControlType == null)
84                                 return;
85 #if NET_2_0
86                         if (partialNameOverride [builder.ID] != null)
87                                 return;
88 #endif
89                         MemberAttributes ma = MemberAttributes.Family;
90                         currentLocation = builder.location;
91                         if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType, ref ma))
92                                 return; // The field or property already exists in a base class and is accesible.
93
94                         CodeMemberField field;
95                         field = new CodeMemberField (builder.ControlType.FullName, builder.ID);
96                         field.Attributes = ma;
97 #if NET_2_0
98                         if (partialClass != null)
99                                 partialClass.Members.Add (field);
100                         else
101 #endif
102                                 mainClass.Members.Add (field);
103                 }
104
105                 bool CheckBaseFieldOrProperty (string id, Type type, ref MemberAttributes ma)
106                 {
107                         FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);
108
109                         Type other = null;
110                         if (fld == null || fld.IsPrivate) {
111                                 PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
112                                 if (prop != null) {
113                                         MethodInfo setm = prop.GetSetMethod (true);
114                                         if (setm != null)
115                                                 other = prop.PropertyType;
116                                 }
117                         } else {
118                                 other = fld.FieldType;
119                         }
120                         
121                         if (other == null)
122                                 return false;
123
124                         if (!other.IsAssignableFrom (type)) {
125 #if NET_2_0
126                                 ma |= MemberAttributes.New;
127                                 return false;
128 #else
129                                 string msg = String.Format ("The base class includes the field '{0}', but its " +
130                                                             "type '{1}' is not compatible with {2}",
131                                                             id, other, type);
132                                 throw new ParseException (currentLocation, msg);
133 #endif
134                         }
135
136                         return true;
137                 }
138
139                 void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr) 
140                 {
141                         if (!builder.haveParserVariable) {
142                                 CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
143                                 p.Name = "__parser";
144                                 p.Type = new CodeTypeReference (typeof (IParserAccessor));
145                                 p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
146                                 builder.methodStatements.Add (p);
147                                 builder.haveParserVariable = true;
148                         }
149
150                         CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
151                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
152                         invoke.Parameters.Add (expr);
153                         builder.methodStatements.Add (invoke);
154                 }
155
156                 void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
157                 {
158                         string tailname = ((builder is RootBuilder) ? "Tree" : ("_" + builder.ID));
159                         CodeMemberMethod method = new CodeMemberMethod ();
160                         builder.method = method;
161                         builder.methodStatements = method.Statements;
162
163                         method.Name = "__BuildControl" + tailname;
164                         method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
165                         Type type = builder.ControlType;
166
167                         /* in the case this is the __BuildControlTree
168                          * method, allow subclasses to insert control
169                          * specific code. */
170                         if (builder is RootBuilder)
171                                 AddStatementsToInitMethod (method);
172
173                         if (builder.HasAspCode) {
174                                 CodeMemberMethod renderMethod = new CodeMemberMethod ();
175                                 builder.renderMethod = renderMethod;
176                                 renderMethod.Name = "__Render" + tailname;
177                                 renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
178                                 CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
179                                 arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
180                                 arg1.Name = "__output";
181                                 CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
182                                 arg2.Type = new CodeTypeReference (typeof (Control));
183                                 arg2.Name = "parameterContainer";
184                                 renderMethod.Parameters.Add (arg1);
185                                 renderMethod.Parameters.Add (arg2);
186                                 mainClass.Members.Add (renderMethod);
187                         }
188                         
189                         if (childrenAsProperties || builder.ControlType == null) {
190                                 string typeString;
191                                 if (builder is RootBuilder)
192                                         typeString = parser.ClassName;
193                                 else {
194                                         if (builder.ControlType != null && builder.isProperty &&
195                                             !typeof (ITemplate).IsAssignableFrom (builder.ControlType))
196                                                 typeString = builder.ControlType.FullName;
197                                         else 
198                                                 typeString = "System.Web.UI.Control";
199                                 }
200
201                                 method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
202                         } else {
203                                 
204                                 if (typeof (Control).IsAssignableFrom (type))
205                                         method.ReturnType = new CodeTypeReference (typeof (Control));
206
207                                 // _ctrl = new $controlType ($parameters);
208                                 //
209                                 CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (type);
210
211                                 object [] atts = type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true);
212                                 if (atts != null && atts.Length > 0) {
213                                         ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
214                                         if (att.NeedsTag)
215                                                 newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
216                                 } else if (builder is DataBindingBuilder) {
217                                         newExpr.Parameters.Add (new CodePrimitiveExpression (0));
218                                         newExpr.Parameters.Add (new CodePrimitiveExpression (1));
219                                 }
220
221                                 method.Statements.Add (new CodeVariableDeclarationStatement (builder.ControlType, "__ctrl"));
222                                 CodeAssignStatement assign = new CodeAssignStatement ();
223                                 assign.Left = ctrlVar;
224                                 assign.Right = newExpr;
225                                 method.Statements.Add (assign);
226                                 
227                                 // this.$builderID = _ctrl;
228                                 //
229                                 CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
230                                 builderID.TargetObject = thisRef;
231                                 builderID.FieldName = builder.ID;
232                                 assign = new CodeAssignStatement ();
233                                 assign.Left = builderID;
234                                 assign.Right = ctrlVar;
235                                 method.Statements.Add (assign);
236                                 if (typeof (UserControl).IsAssignableFrom (type)) {
237                                         CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
238                                         mref.TargetObject = builderID;
239                                         mref.MethodName = "InitializeAsUserControl";
240                                         CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
241                                         initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
242                                         method.Statements.Add (initAsControl);
243                                 }
244
245 #if NET_2_0
246                                 // _ctrl.SkinID = $value
247                                 // _ctrl.ApplyStyleSheetSkin (this);
248                                 //
249                                 // the SkinID assignment needs to come
250                                 // before the call to
251                                 // ApplyStyleSheetSkin, for obvious
252                                 // reasons.  We skip SkinID in
253                                 // CreateAssignStatementsFromAttributes
254                                 // below.
255                                 // 
256                                 if (builder.attribs != null) {
257                                         string skinid = builder.attribs ["skinid"] as string;
258                                         if (skinid != null)
259                                                 CreateAssignStatementFromAttribute (builder, "skinid");
260                                 }
261                                 if (typeof (WebControl).IsAssignableFrom (type)) {
262                                         CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
263                                         if (typeof (Page).IsAssignableFrom (parser.BaseType))
264                                                 applyStyleSheetSkin.Parameters.Add (thisRef);
265                                         else
266                                                 applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
267                                         method.Statements.Add (applyStyleSheetSkin);
268                                 }
269 #endif
270
271 #if NET_2_0
272                                 if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
273                                         CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (thisRef, "ContentPlaceHolders");
274                                         CodeMethodInvokeExpression addPlaceholder = new CodeMethodInvokeExpression (prop, "Add");
275                                         addPlaceholder.Parameters.Add (ctrlVar);
276                                         method.Statements.Add (addPlaceholder);
277
278
279                                         CodeConditionStatement condStatement;
280
281                                         // Add the __Template_* field
282                                         CodeMemberField fld = new CodeMemberField (typeof (ITemplate), "__Template_" + builder.ID);
283                                         fld.Attributes = MemberAttributes.Private;
284                                         mainClass.Members.Add (fld);
285
286                                         CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
287                                         templateID.TargetObject = thisRef;
288                                         templateID.FieldName = "__Template_" + builder.ID;
289
290                                         // if ((this.ContentTemplates != null)) {
291                                         //      this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
292                                         // }
293                                         //
294                                         CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
295                                         contentTemplates.TargetObject = thisRef;
296                                         contentTemplates.FieldName = "ContentTemplates";
297
298                                         CodeIndexerExpression indexer = new CodeIndexerExpression ();
299                                         indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
300                                         indexer.Indices.Add (new CodePrimitiveExpression (builder.ID));
301
302                                         assign = new CodeAssignStatement ();
303                                         assign.Left = templateID;
304                                         assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);
305
306                                         condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
307                                                                                                                       CodeBinaryOperatorType.IdentityInequality,
308                                                                                                                       new CodePrimitiveExpression (null)),
309                                                                                     assign);
310
311                                         method.Statements.Add (condStatement);
312
313                                         // if ((this.__Template_mainContent != null)) {
314                                         //      this.__Template_mainContent.InstantiateIn(__ctrl);
315                                         // }
316                                         // and also set things up such that any additional code ends up in:
317                                         // else {
318                                         //      ...
319                                         // }
320                                         //
321                                         CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
322                                         methodRef.TargetObject = templateID;
323                                         methodRef.MethodName = "InstantiateIn";
324
325                                         CodeMethodInvokeExpression instantiateInInvoke;
326                                         instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);
327
328                                         condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
329                                                                                                                       CodeBinaryOperatorType.IdentityInequality,
330                                                                                                                       new CodePrimitiveExpression (null)),
331                                                                                     new CodeExpressionStatement (instantiateInInvoke));
332                                         method.Statements.Add (condStatement);
333
334                                         // this is the bit that causes the following stuff to end up in the else { }
335                                         builder.methodStatements = condStatement.FalseStatements;
336
337                                         // __ctrl.TemplateControl = this;
338                                         assign = new CodeAssignStatement ();
339                                         assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
340                                         assign.Right = thisRef;
341
342                                         method.Statements.Add (assign);
343                                 }
344 #endif
345                         }
346
347                         mainClass.Members.Add (method);
348                 }
349
350                 protected virtual void AddStatementsToInitMethod (CodeMemberMethod method)
351                 {
352                 }
353
354                 void AddLiteralSubObject (ControlBuilder builder, string str)
355                 {
356                         if (!builder.HasAspCode) {
357                                 CodeObjectCreateExpression expr;
358                                 expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
359                                 AddParsedSubObjectStmt (builder, expr);
360                         } else {
361                                 CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
362                                 methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
363                                 methodRef.MethodName = "Write";
364
365                                 CodeMethodInvokeExpression expr;
366                                 expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
367                                 builder.renderMethod.Statements.Add (expr);
368                         }
369                 }
370
371                 string TrimDB (string value)
372                 {
373                         string str = value.Trim ();
374                         str = str.Substring (3);
375                         return str.Substring (0, str.Length - 2);
376                 }
377
378                 string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
379                 {
380                         value = TrimDB (value);
381                         CodeMemberMethod method;
382                         string dbMethodName = builder.method.Name + "_DB_" + dataBoundAtts++;
383 #if NET_2_0
384                         bool need_if = false;
385                         value = value.Trim ();
386                         if (StrUtils.StartsWith (value, "Bind")) {
387                                 value = "Eval" + value.Substring (4);
388                                 need_if = true;
389                         }
390 #endif
391
392                         method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
393
394                         CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
395
396                         // This should be a CodePropertyReferenceExpression for properties... but it works anyway
397                         CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);
398
399                         CodeExpression expr;
400                         if (type == typeof (string)) {
401                                 CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
402                                 CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
403                                 tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
404                                 tostring.Parameters.Add (new CodeSnippetExpression (value));
405                                 expr = tostring;
406                         } else {
407                                 CodeSnippetExpression snippet = new CodeSnippetExpression (value);
408                                 expr = new CodeCastExpression (type, snippet);
409                         }
410
411                         CodeAssignStatement assign = new CodeAssignStatement (field, expr);
412 #if NET_2_0
413                         if (need_if) {
414                                 CodeExpression page = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Page");
415                                 CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
416                                 CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
417                                 CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
418                                 method.Statements.Add (ccs);
419                         }
420                         else
421 #endif
422                                 method.Statements.Add (assign);
423
424                         mainClass.Members.Add (method);
425                         return method.Name;
426                 }
427
428                 void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
429                 {
430                         CodeMemberMethod method = builder.method;
431                         bool isWritable = IsWritablePropertyOrField (member);
432                         if (isDataBound && isWritable) {
433                                 string dbMethodName = DataBoundProperty (builder, type, var_name, att);
434                                 AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
435                                 return;
436                         }
437 #if NET_2_0
438                         else if (isExpression && isWritable) {
439                                 AddExpressionAssign (method, member, type, var_name, att);
440                                 return;
441                         }
442 #endif
443                         
444                         CodeAssignStatement assign = new CodeAssignStatement ();
445                         assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
446                         currentLocation = builder.location;
447                         assign.Right = GetExpressionFromString (type, att, member);
448
449                         method.Statements.Add (assign);
450                 }
451
452                 bool IsDataBound (string value)
453                 {
454                         if (value == null || value == "")
455                                 return false;
456
457                         string str = value.Trim ();
458                         return (StrUtils.StartsWith (str, "<%#") && StrUtils.EndsWith (str, "%>"));
459                 }
460
461 #if NET_2_0
462                 bool IsExpression (string value)
463                 {
464                         if (value == null || value == "")
465                                 return false;
466                         string str = value.Trim ();
467                         return (StrUtils.StartsWith (str, "<%$") && StrUtils.EndsWith (str, "%>"));
468                 }               
469
470                 void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
471                 {
472                         string str = value.Trim ();
473                         str = str.Substring (3).Trim ();        // eats "<%#"
474                         if (StrUtils.StartsWith (str, "Bind")) {
475                                 Match match = bindRegex.Match (str);
476                                 if (match.Success) {
477                                         string bindingName = match.Groups [1].Value;
478                                         
479                                         TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
480                                         if (templateBuilder == null || templateBuilder.BindingDirection == BindingDirection.OneWay)
481                                                 throw new HttpException ("Bind expression not allowed in this context.");
482                                                 
483                                         string id = builder.attribs ["ID"] as string;
484                                         if (id == null)
485                                                 throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
486                                         
487                                         templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
488                                 }
489                         }
490                 }
491 #endif
492
493                 /*
494                 static bool InvariantCompare (string a, string b)
495                 {
496                         return (0 == String.Compare (a, b, false, CultureInfo.InvariantCulture));
497                 }
498                 */
499
500                 static bool InvariantCompareNoCase (string a, string b)
501                 {
502                         return (0 == String.Compare (a, b, true, CultureInfo.InvariantCulture));
503                 }
504
505                 static MemberInfo GetFieldOrProperty (Type type, string name)
506                 {
507                         MemberInfo member = null;
508                         try {
509                                 member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
510                         } catch {}
511                         
512                         if (member != null)
513                                 return member;
514
515                         try {
516                                 member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
517                         } catch {}
518
519                         return member;
520                 }
521
522                 static bool IsWritablePropertyOrField (MemberInfo member)
523                 {
524                         PropertyInfo pi = member as PropertyInfo;
525                         if (pi != null)
526                                 return pi.CanWrite;
527                         FieldInfo fi = member as FieldInfo;
528                         if (fi != null)
529                                 return !fi.IsInitOnly;
530                         throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
531                 }
532
533                 bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
534                                                  string attValue, string prefix)
535                 {
536                         int hyphen = id.IndexOf ('-');
537                         bool isPropertyInfo = (member is PropertyInfo);
538                         bool isDataBound = IsDataBound (attValue);
539 #if NET_2_0
540                         bool isExpression = !isDataBound && IsExpression (attValue);
541 #else
542                         bool isExpression = false;
543 #endif
544                         Type type;
545                         if (isPropertyInfo) {
546                                 type = ((PropertyInfo) member).PropertyType;
547                         } else {
548                                 type = ((FieldInfo) member).FieldType;
549                         }
550
551                         if (InvariantCompareNoCase (member.Name, id)) {
552 #if NET_2_0
553                                 if (isDataBound)
554                                         RegisterBindingInfo (builder, member.Name, ref attValue);
555                                 
556 #endif
557                                 if (!IsWritablePropertyOrField (member))
558                                         return false;
559
560                                 AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
561                                 return true;
562                         }
563                         
564                         if (hyphen == -1)
565                                 return false;
566
567                         string prop_field = id.Replace ("-", ".");
568                         string [] parts = prop_field.Split (new char [] {'.'});
569                         int length = parts.Length;
570                         if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
571                                 return false;
572
573                         if (length > 2) {
574                                 MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
575                                 if (sub_member == null)
576                                         return false;
577
578                                 string new_prefix = prefix + parts [0] + ".";
579                                 string new_id = id.Substring (hyphen + 1);
580                                 return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
581                         }
582
583                         MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
584                         if (!(subpf is PropertyInfo))
585                                 return false;
586
587                         PropertyInfo subprop = (PropertyInfo) subpf;
588                         if (subprop.CanWrite == false)
589                                 return false;
590
591                         bool is_bool = (subprop.PropertyType == typeof (bool));
592                         if (!is_bool && attValue == null)
593                                 return false; // Font-Size -> Font-Size="" as html
594
595                         string val = attValue;
596                         if (attValue == null && is_bool)
597                                 val = "true"; // Font-Bold <=> Font-Bold="true"
598 #if NET_2_0
599                         if (isDataBound) RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);
600 #endif
601                         AddCodeForPropertyOrField (builder, subprop.PropertyType,
602                                                    prefix + member.Name + "." + subprop.Name,
603                                                    val, subprop, isDataBound, isExpression);
604
605                         return true;
606                 }
607
608 #if NET_2_0
609                 void AddExpressionAssign (CodeMemberMethod method, MemberInfo member, Type type, string name, string value)
610                 {
611                         CodeAssignStatement assign = new CodeAssignStatement ();
612                         assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);
613
614                         // First let's find the correct expression builder
615                         string expr = value.Substring (3, value.Length - 5).Trim ();
616                         int colon = expr.IndexOf (':');
617                         if (colon == -1)
618                                 return;
619                         string prefix = expr.Substring (0, colon).Trim ();
620                         
621                         System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration ("");
622                         if (config == null)
623                                 return;
624                         CompilationSection cs = (CompilationSection)config.GetSection ("system.web/compilation");
625                         if (cs == null)
626                                 return;
627                         if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
628                                 return;
629
630                         System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
631                         if (ceb == null)
632                                 return;
633                         string builderType = ceb.Type;
634
635                         Type t;
636                         try {
637                                 t = System.Type.GetType (builderType, true);
638                         } catch (Exception e) {
639                                 throw new HttpException (
640                                         String.Format ("Failed to load expression builder type `{0}'", builderType), e);
641                         }
642
643                         if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
644                                 throw new HttpException (
645                                         String.Format (
646                                                 "Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder",
647                                                 builderType));
648
649                         System.Web.Compilation.ExpressionBuilder eb = null;
650                         object parsedData;
651                         ExpressionBuilderContext ctx;
652                         
653                         try {
654                                 eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
655                                 ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
656                                 parsedData = eb.ParseExpression (expr.Substring (colon + 1).Trim (), type, ctx);
657                         } catch (Exception e) {
658                                 throw new HttpException (
659                                         String.Format ("Failed to create an instance of type `{0}'", builderType), e);
660                         }
661                         // FIXME: create and pass an instance of BoundPropertyEntry
662                         CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
663                         convert.Method = new CodeMethodReferenceExpression (
664                                 new CodeTypeReferenceExpression (typeof(Convert)),
665                                 "ToString");
666                         convert.Parameters.Add (eb.GetCodeExpression (null, parsedData, ctx));
667                         convert.Parameters.Add (
668                                 new CodeFieldReferenceExpression (
669                                         new CodeTypeReferenceExpression ("System.Globalization.CultureInfo"),
670                                         "CurrentCulture"));
671                         assign.Right = convert;
672                         
673                         method.Statements.Add (assign);
674                 }
675
676                 void AssignPropertyFromResources (CodeMemberMethod method, MemberInfo mi, string attvalue, string varname)
677                 {
678                         string resname = String.Format ("{0}.{1}", attvalue, mi.Name);
679                         bool isProperty = mi.MemberType == MemberTypes.Property;
680                         bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
681
682                         if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
683                                 return;
684                         
685                         Type member_type = null;
686                         if (isProperty) {
687                                 PropertyInfo pi = mi as PropertyInfo;
688                                 member_type = pi.PropertyType;
689                         } else if (isField) { 
690                                 FieldInfo fi = mi as FieldInfo;
691                                 member_type = fi.FieldType;
692                         } else // should never happen
693                                 return;
694
695                         // __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
696                         string inputFile = parser.InputFile;
697                         string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
698         
699                         if (StrUtils.StartsWith (inputFile, physPath))
700                                 inputFile = parser.InputFile.Substring (physPath.Length - 1);
701                          else
702                                 return;
703                         
704                         object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
705                         if (obj == null)
706                                 return;
707                         
708                         CodeAssignStatement assign = new CodeAssignStatement ();
709                         assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
710                         CodeMethodInvokeExpression getlro = new CodeMethodInvokeExpression (
711                                 new CodeThisReferenceExpression (),
712                                 "GetLocalResourceObject",
713                                 new CodeExpression [] { new CodePrimitiveExpression (resname) });
714                         
715                         CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
716                         convert.Method = new CodeMethodReferenceExpression (
717                                 new CodeTypeReferenceExpression (typeof(System.Convert)),
718                                 "ToString");
719                         convert.Parameters.Add (getlro);
720                         assign.Right = convert;
721                         
722 //                      assign.Left = new CodeVariableReferenceExpression (varname);
723 //                      assign.Right = new CodeMethodInvokeExpression (
724 //                              new CodeThisReferenceExpression (),
725 //                              "GetLocalResourceObject",
726 //                              new CodeExpression [] { new CodePrimitiveExpression (resname) });
727 //                      method.Statements.Add (assign);
728
729 //                      // if (localResourceObject != null && localResourceObject.GetType() == typeof(member_type))
730 //                      CodeConditionStatement ccs = new CodeConditionStatement ();
731 //                      CodeBinaryOperatorExpression exp1 = new CodeBinaryOperatorExpression (
732 //                              new CodeVariableReferenceExpression (varname),
733 //                              CodeBinaryOperatorType.IdentityInequality,
734 //                              new CodePrimitiveExpression (null));
735                         
736 //                      CodeBinaryOperatorExpression exp2 = new CodeBinaryOperatorExpression (
737 //                              new CodeMethodInvokeExpression (
738 //                                      new CodeVariableReferenceExpression (varname),
739 //                                      "GetType",
740 //                                      new CodeExpression [] {}),
741 //                              CodeBinaryOperatorType.IdentityEquality,
742 //                              new CodeTypeOfExpression (
743 //                                      new CodeTypeReference (member_type.ToString ())));
744 //                      ccs.Condition = new CodeBinaryOperatorExpression (
745 //                              exp1,
746 //                              CodeBinaryOperatorType.BooleanAnd,
747 //                              exp2);
748                         
749 //                      //   ctrlVar.Property = (member_type)obj;
750 //                      assign = new CodeAssignStatement ();
751 //                      assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
752 //                      assign.Right = new CodeCastExpression (
753 //                              member_type.ToString (),
754 //                              new CodeVariableReferenceExpression (varname));
755 //                      ccs.TrueStatements.Add (assign);
756                         method.Statements.Add (assign);
757                 }
758                 
759                 void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
760                 {
761                         if (attvalue == null || attvalue.Length == 0)
762                                 return;
763                         
764                         Type controlType = builder.ControlType;
765                         if (controlType == null)
766                                 return;
767
768                         // object obj = null;
769                         
770                         // Process all public fields and properties of the control. We don't use GetMembers to make the code
771                         // faster
772                         FieldInfo [] fields = controlType.GetFields (
773                                 BindingFlags.Instance | BindingFlags.Static |
774                                 BindingFlags.Public | BindingFlags.FlattenHierarchy);
775                         PropertyInfo [] properties = controlType.GetProperties (
776                                 BindingFlags.Instance | BindingFlags.Static |
777                                 BindingFlags.Public | BindingFlags.FlattenHierarchy);
778
779                         if (fields.Length > 0 || properties.Length > 0) {
780                                 CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement (
781                                         typeof (object),
782                                         "localResourceObject",
783                                         new CodePrimitiveExpression (null));
784                                 builder.method.Statements.Add (cvds);
785                         }
786                         
787                         foreach (FieldInfo fi in fields)
788                                 AssignPropertyFromResources (builder.method, fi, attvalue, "localResourceObject");
789                         foreach (PropertyInfo pi in properties)
790                                 AssignPropertyFromResources (builder.method, pi, attvalue, "localResourceObject");
791                 }
792 #endif
793                 
794                 void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
795                 {
796                         //"__ctrl.{0} += new {1} (this.{2});"
797                         CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
798
799                         CodeDelegateCreateExpression create;
800                         create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
801
802                         CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
803                         method.Statements.Add (attach);
804                 }
805                 
806                 void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
807                 {
808                         EventInfo [] ev_info = null;
809                         Type type = builder.ControlType;
810
811                         string attvalue = builder.attribs [id] as string;
812                         if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
813                                 if (ev_info == null)
814                                         ev_info = type.GetEvents ();
815
816                                 string id_as_event = id.Substring (2);
817                                 foreach (EventInfo ev in ev_info){
818                                         if (InvariantCompareNoCase (ev.Name, id_as_event)){
819                                                 AddEventAssign (builder.method,
820                                                                 ev.Name,
821                                                                 ev.EventHandlerType,
822                                                                 attvalue);
823                                                 
824                                                 return;
825                                         }
826                                 }
827
828                         }
829
830 #if NET_2_0
831                         if (id.ToLower () == "meta:resourcekey") {
832                                 AssignPropertiesFromResources (builder, attvalue);
833                                 return;
834                         }
835 #endif
836                         
837                         int hyphen = id.IndexOf ('-');
838                         string alt_id = id;
839                         if (hyphen != -1)
840                                 alt_id = id.Substring (0, hyphen);
841
842                         MemberInfo fop = GetFieldOrProperty (type, alt_id);
843                         if (fop != null) {
844                                 if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
845                                         return;
846                         }
847
848                         if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
849                                 throw new ParseException (builder.location, "Unrecognized attribute: " + id);
850
851                         string val;
852                         CodeMemberMethod method = builder.method;
853                         bool databound = IsDataBound (attvalue);
854
855                         if (databound) {
856                                 val = attvalue.Substring (3);
857                                 val = val.Substring (0, val.Length - 2);
858                                 CreateDBAttributeMethod (builder, id, val);
859                         } else {
860                                 CodeCastExpression cast;
861                                 CodeMethodReferenceExpression methodExpr;
862                                 CodeMethodInvokeExpression expr;
863
864                                 cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
865                                 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
866                                 expr = new CodeMethodInvokeExpression (methodExpr);
867                                 expr.Parameters.Add (new CodePrimitiveExpression (id));
868                                 expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
869                                 method.Statements.Add (expr);
870                         }
871
872                 }
873
874                 protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
875                 {
876                         this.dataBoundAtts = 0;
877                         IDictionary atts = builder.attribs;
878                         if (atts == null || atts.Count == 0)
879                                 return;
880
881                         foreach (string id in atts.Keys) {
882                                 if (InvariantCompareNoCase (id, "runat"))
883                                         continue;
884
885 #if NET_2_0
886                                 /* we skip SkinID here as it's assigned in BuildControlTree */
887                                 if (InvariantCompareNoCase (id, "skinid"))
888                                         continue;
889 #endif
890                                 CreateAssignStatementFromAttribute (builder, id);
891                         }
892                 }
893
894                 void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
895                 {
896                         if (code == null || code.Trim () == "")
897                                 return;
898
899                         string id = builder.GetNextID (null);
900                         string dbMethodName = "__DataBind_" + id;
901                         CodeMemberMethod method = builder.method;
902                         AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
903
904                         method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
905                         CodeCastExpression cast;
906                         CodeMethodReferenceExpression methodExpr;
907                         CodeMethodInvokeExpression expr;
908
909                         CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
910                         cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
911                         methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
912                         expr = new CodeMethodInvokeExpression (methodExpr);
913                         expr.Parameters.Add (new CodePrimitiveExpression (attr));
914                         CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
915                         tostring.Method = new CodeMethodReferenceExpression (
916                                                         new CodeTypeReferenceExpression (typeof (Convert)),
917                                                         "ToString");
918                         tostring.Parameters.Add (new CodeSnippetExpression (code));
919                         expr.Parameters.Add (tostring);
920                         method.Statements.Add (expr);
921                         mainClass.Members.Add (method);
922                 }
923
924                 void AddRenderControl (ControlBuilder builder)
925                 {
926                         CodeIndexerExpression indexer = new CodeIndexerExpression ();
927                         indexer.TargetObject = new CodePropertyReferenceExpression (
928                                                         new CodeArgumentReferenceExpression ("parameterContainer"),
929                                                         "Controls");
930                                                         
931                         indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
932                         
933                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
934                         invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
935                         builder.renderMethod.Statements.Add (invoke);
936                         builder.renderIndex++;
937                 }
938
939                 protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
940                 {
941                         if (parent == null || child == null)
942                                 return;
943                         CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
944                         CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
945
946                         object [] atts = null;
947                         
948                         if (child.ControlType != null)
949                                 child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
950                         if (atts != null && atts.Length > 0) {
951                                 PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
952                                 CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
953                                 CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
954                                 build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
955                                 build.Parameters.Add (new CodePrimitiveExpression (child.ID));
956 #if NET_1_1
957                                 if (pca.Shared)
958                                         build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
959                                 else
960 #endif
961                                         build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
962                                         
963                                 build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
964                                 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
965                                 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
966                                 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
967                                 build.Parameters.Add (new CodeDelegateCreateExpression (
968                                                               new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
969                                                               thisRef, child.method.Name));
970                                 
971                                 parent.methodStatements.Add (build);
972                                 if (parent.HasAspCode)
973                                         AddRenderControl (parent);
974                                 return;
975                         }
976                                 
977                         if (child.isProperty || parent.ChildrenAsProperties) {
978                                 expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
979                                 parent.methodStatements.Add (expr);
980                                 return;
981                         }
982
983                         parent.methodStatements.Add (expr);
984                         CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
985                         if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
986                                 AddParsedSubObjectStmt (parent, field);
987                         } else {
988                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
989                                 invoke.Parameters.Add (field);
990                                 parent.methodStatements.Add (invoke);
991                         }
992                                 
993                         if (parent.HasAspCode)
994                                 AddRenderControl (parent);
995                 }
996
997                 void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
998                 {
999                         CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1000
1001                         CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1002                         newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1003
1004                         CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1005                         newCompiled.Parameters.Add (newBuild);
1006
1007                         CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1008                         method.Statements.Add (assign);
1009                 }
1010
1011 #if NET_2_0
1012                 void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
1013                 {
1014                         CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1015
1016                         CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1017                         newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1018
1019                         CodeObjectCreateExpression newExtract = new CodeObjectCreateExpression (typeof (ExtractTemplateValuesMethod));
1020                         newExtract.Parameters.Add (new CodeMethodReferenceExpression (thisRef, extractMethodName));
1021
1022                         CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
1023                         newCompiled.Parameters.Add (newBuild);
1024                         newCompiled.Parameters.Add (newExtract);
1025                         
1026                         CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1027                         method.Statements.Add (assign);
1028                 }
1029                 
1030                 string CreateExtractValuesMethod (TemplateBuilder builder)
1031                 {
1032                         CodeMemberMethod method = new CodeMemberMethod ();
1033                         method.Name = "__ExtractValues_" + builder.ID;
1034                         method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1035                         method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
1036                         
1037                         CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
1038                         arg.Type = new CodeTypeReference (typeof (Control));
1039                         arg.Name = "__container";
1040                         method.Parameters.Add (arg);
1041                         mainClass.Members.Add (method);
1042                         
1043                         CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
1044                         newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
1045                         method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
1046                         CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
1047                         
1048                         if (builder.Bindings != null) {
1049                                 Hashtable hash = new Hashtable ();
1050                                 foreach (TemplateBinding binding in builder.Bindings) {
1051                                         CodeConditionStatement sif;
1052                                         CodeVariableReferenceExpression control;
1053                                         CodeAssignStatement assign;
1054
1055                                         if (hash [binding.ControlId] == null) {
1056
1057                                                 CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
1058                                                 method.Statements.Add (dec);
1059                                                 CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
1060                                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
1061                                                 invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
1062
1063                                                 assign = new CodeAssignStatement ();
1064                                                 control = new CodeVariableReferenceExpression (binding.ControlId);
1065                                                 assign.Left = control;
1066                                                 assign.Right = new CodeCastExpression (binding.ControlType, invoke);
1067                                                 method.Statements.Add (assign);
1068
1069                                                 sif = new CodeConditionStatement ();
1070                                                 sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
1071
1072                                                 method.Statements.Add (sif);
1073
1074                                                 hash [binding.ControlId] = sif;
1075                                         }
1076
1077                                         sif = (CodeConditionStatement) hash [binding.ControlId];
1078                                         control = new CodeVariableReferenceExpression (binding.ControlId);
1079                                         assign = new CodeAssignStatement ();
1080                                         assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
1081                                         assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
1082                                         sif.TrueStatements.Add (assign);
1083                                 }
1084                         }
1085
1086                         method.Statements.Add (new CodeMethodReturnStatement (tableExp));
1087                         return method.Name;
1088                 }
1089
1090                 void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
1091                 {
1092                         CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1093                         newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1094
1095                         CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1096                         newCompiled.Parameters.Add (newBuild);
1097                         
1098                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
1099                         invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
1100                         invoke.Parameters.Add (newCompiled);
1101
1102                         method.Statements.Add (invoke);
1103                 }
1104 #endif
1105
1106                 void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
1107                 {
1108                         if (cr.Code == null || cr.Code.Trim () == "")
1109                                 return;
1110
1111                         if (!cr.IsAssign) {
1112                                 CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
1113                                 parent.renderMethod.Statements.Add (code);
1114                                 return;
1115                         }
1116
1117                         CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
1118                         expr.Method = new CodeMethodReferenceExpression (
1119                                                         new CodeArgumentReferenceExpression ("__output"),
1120                                                         "Write");
1121
1122                         expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
1123                         parent.renderMethod.Statements.Add (expr);
1124                 }
1125
1126                 static Type GetContainerType (ControlBuilder builder)
1127                 {
1128                         TemplateBuilder tb = builder as TemplateBuilder;
1129                         if (tb != null && tb.ContainerType != null)
1130                                 return tb.ContainerType;
1131
1132                         Type type = builder.BindingContainerType;
1133
1134                         PropertyInfo prop = type.GetProperty ("Items", noCaseFlags & ~BindingFlags.NonPublic);
1135                         if (prop == null)
1136                                 return type;
1137
1138                         Type ptype = prop.PropertyType;
1139                         if (!typeof (ICollection).IsAssignableFrom (ptype))
1140                                 return type;
1141
1142                         prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
1143                         if (prop == null)
1144                                 return type;
1145
1146                         return prop.PropertyType;
1147                 }
1148                 
1149                 CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
1150                 {
1151                         CodeMemberMethod method = new CodeMemberMethod ();
1152                         method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1153                         method.Name = name;
1154                         method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
1155                         method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
1156
1157                         CodeTypeReference containerRef = new CodeTypeReference (container);
1158                         CodeTypeReference targetRef = new CodeTypeReference (target);
1159
1160                         CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
1161                         decl.Name = "Container";
1162                         decl.Type = containerRef;
1163                         method.Statements.Add (decl);
1164
1165                         decl = new CodeVariableDeclarationStatement();
1166                         decl.Name = "target";
1167                         decl.Type = targetRef;
1168                         method.Statements.Add (decl);
1169
1170                         CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1171                         CodeAssignStatement assign = new CodeAssignStatement ();
1172                         assign.Left = targetExpr;
1173                         assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
1174                         method.Statements.Add (assign);
1175
1176                         assign = new CodeAssignStatement ();
1177                         assign.Left = new CodeVariableReferenceExpression ("Container");
1178                         assign.Right = new CodeCastExpression (containerRef,
1179                                                 new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
1180                         method.Statements.Add (assign);
1181
1182                         return method;
1183                 }
1184
1185                 void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
1186                 {
1187                         if (db.Code == null || db.Code.Trim () == "")
1188                                 return;
1189
1190                         EnsureID (db);
1191                         CreateField (db, false);
1192
1193                         string dbMethodName = "__DataBind_" + db.ID;
1194                         // Add the method that builds the DataBoundLiteralControl
1195                         InitMethod (db, false, false);
1196                         CodeMemberMethod method = db.method;
1197                         AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
1198                         method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1199
1200                         // Add the DataBind handler
1201                         method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
1202
1203                         CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1204                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1205                         invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
1206                         invoke.Parameters.Add (new CodePrimitiveExpression (0));
1207
1208                         CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
1209                         tostring.Method = new CodeMethodReferenceExpression (
1210                                                         new CodeTypeReferenceExpression (typeof (Convert)),
1211                                                         "ToString");
1212                         tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
1213                         invoke.Parameters.Add (tostring);
1214                         method.Statements.Add (invoke);
1215                         
1216                         mainClass.Members.Add (method);
1217
1218                         AddChildCall (builder, db);
1219                 }
1220
1221                 void FlushText (ControlBuilder builder, StringBuilder sb)
1222                 {
1223                         if (sb.Length > 0) {
1224                                 AddLiteralSubObject (builder, sb.ToString ());
1225                                 sb.Length = 0;
1226                         }
1227                 }
1228
1229                 protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
1230                 {
1231                         EnsureID (builder);
1232                         bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
1233                         if (!isTemplate && !inTemplate) {
1234                                 CreateField (builder, true);
1235                         } else if (!isTemplate) {
1236                                 builder.ID = builder.GetNextID (null);
1237                                 CreateField (builder, false);
1238                         }
1239
1240                         InitMethod (builder, isTemplate, childrenAsProperties);
1241                         if (!isTemplate || builder.GetType () == typeof (RootBuilder))
1242                                 CreateAssignStatementsFromAttributes (builder);
1243
1244                         if (builder.Children != null && builder.Children.Count > 0) {
1245                                 ArrayList templates = null;
1246
1247                                 StringBuilder sb = new StringBuilder ();
1248                                 foreach (object b in builder.Children) {
1249
1250                                         if (b is string) {
1251                                                 sb.Append ((string) b);
1252                                                 continue;
1253                                         }
1254
1255                                         FlushText (builder, sb);
1256                                         if (b is ObjectTagBuilder) {
1257                                                 ProcessObjectTag ((ObjectTagBuilder) b);
1258                                                 continue;
1259                                         }
1260
1261                                         StringPropertyBuilder pb = b as StringPropertyBuilder;
1262                                         if (pb != null){
1263                                                 if (pb.Children != null && pb.Children.Count > 0) {
1264                                                         StringBuilder asb = new StringBuilder ();
1265                                                         foreach (string s in pb.Children)
1266                                                                 asb.Append (s);
1267                                                         CodeMemberMethod method = builder.method;
1268                                                         CodeAssignStatement assign = new CodeAssignStatement ();
1269                                                         assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
1270                                                         assign.Right = new CodePrimitiveExpression (asb.ToString ());
1271                                                         method.Statements.Add (assign);
1272                                                 }
1273                                                 continue;
1274                                         }
1275
1276 #if NET_2_0
1277                                         if (b is ContentBuilderInternal) {
1278                                                 ContentBuilderInternal cb = (ContentBuilderInternal) b;
1279                                                 CreateControlTree (cb, false, true);
1280                                                 AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
1281                                                 continue;
1282                                         }
1283 #endif
1284
1285                                         if (b is TemplateBuilder) {
1286                                                 if (templates == null)
1287                                                         templates = new ArrayList ();
1288
1289                                                 templates.Add (b);
1290                                                 continue;
1291                                         }
1292
1293                                         if (b is CodeRenderBuilder) {
1294                                                 AddCodeRender (builder, (CodeRenderBuilder) b);
1295                                                 continue;
1296                                         }
1297
1298                                         if (b is DataBindingBuilder) {
1299                                                 AddDataBindingLiteral (builder, (DataBindingBuilder) b);
1300                                                 continue;
1301                                         }
1302                                         
1303                                         if (b is ControlBuilder) {
1304                                                 ControlBuilder child = (ControlBuilder) b;
1305                                                 CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
1306                                                 AddChildCall (builder, child);
1307                                                 continue;
1308                                         }
1309
1310                                         throw new Exception ("???");
1311                                 }
1312
1313                                 FlushText (builder, sb);
1314
1315                                 if (templates != null) {
1316                                         foreach (TemplateBuilder b in templates) {
1317                                                 CreateControlTree (b, true, false);
1318 #if NET_2_0
1319                                                 if (b.BindingDirection == BindingDirection.TwoWay) {
1320                                                         string extractMethod = CreateExtractValuesMethod (b);
1321                                                         AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
1322                                                 }
1323                                                 else
1324 #endif
1325                                                 AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
1326                                         }
1327                                 }
1328
1329                         }
1330
1331                         if (builder.defaultPropertyBuilder != null) {
1332                                 ControlBuilder b = builder.defaultPropertyBuilder;
1333                                 CreateControlTree (b, false, true);
1334                                 AddChildCall (builder, b);
1335                         }
1336
1337                         if (builder.HasAspCode) {
1338                                 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1339                                 m.TargetObject = thisRef;
1340                                 m.MethodName = builder.renderMethod.Name;
1341
1342                                 CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
1343                                 create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
1344                                 create.TargetObject = thisRef;
1345                                 create.MethodName = builder.renderMethod.Name;
1346
1347                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1348                                 invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
1349                                 invoke.Parameters.Add (create);
1350
1351                                 builder.methodStatements.Add (invoke);
1352                         }
1353                         
1354                         if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
1355                                 builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1356                 }
1357                 
1358                 protected internal override void CreateMethods ()
1359                 {
1360                         base.CreateMethods ();
1361
1362                         CreateProperties ();
1363                         CreateControlTree (parser.RootBuilder, false, false);
1364                         CreateFrameworkInitializeMethod ();
1365                 }
1366
1367                 void CallBaseFrameworkInitialize (CodeMemberMethod method)
1368                 {
1369                         CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
1370                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
1371                         method.Statements.Add (invoke);
1372                 }
1373
1374                 void CreateFrameworkInitializeMethod ()
1375                 {
1376                         CodeMemberMethod method = new CodeMemberMethod ();
1377                         method.Name = "FrameworkInitialize";
1378                         method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1379                         PrependStatementsToFrameworkInitialize (method);
1380                         CallBaseFrameworkInitialize (method);
1381                         AppendStatementsToFrameworkInitialize (method);
1382                         mainClass.Members.Add (method);
1383                 }
1384
1385                 protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
1386                 {
1387                 }
1388
1389                 protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
1390                 {
1391                         if (!parser.EnableViewState) {
1392                                 CodeAssignStatement stmt = new CodeAssignStatement ();
1393                                 stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
1394                                 stmt.Right = new CodePrimitiveExpression (false);
1395                                 method.Statements.Add (stmt);
1396                         }
1397
1398                         CodeMethodReferenceExpression methodExpr;
1399                         methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
1400                         CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
1401                         method.Statements.Add (new CodeExpressionStatement (expr));
1402                 }
1403
1404                 protected override void AddApplicationAndSessionObjects ()
1405                 {
1406                         foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
1407                                 CreateFieldForObject (tag.Type, tag.ObjectID);
1408                                 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
1409                         }
1410
1411                         foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
1412                                 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
1413                         }
1414                 }
1415
1416                 protected void ProcessObjectTag (ObjectTagBuilder tag)
1417                 {
1418                         string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
1419                         CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
1420                 }
1421
1422                 void CreateProperties ()
1423                 {
1424                         if (!parser.AutoEventWireup) {
1425                                 CreateAutoEventWireup ();
1426                         } else {
1427                                 CreateAutoHandlers ();
1428                         }
1429
1430                         CreateApplicationInstance ();
1431                         CreateTemplateSourceDirectory ();
1432                 }
1433
1434                 void CreateTemplateSourceDirectory ()
1435                 {
1436                         CodeMemberProperty prop = new CodeMemberProperty ();
1437                         prop.Type = new CodeTypeReference (typeof (string));
1438                         prop.Name = "TemplateSourceDirectory";
1439                         prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
1440
1441                         // if ((this.Parent != null))
1442                         //   return this.Parent.TemplateSourceDirectory;
1443                         CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression ();
1444                         parentField.TargetObject = thisRef;
1445                         parentField.FieldName = "Parent";
1446                         
1447                         CodeFieldReferenceExpression tsdField = new CodeFieldReferenceExpression ();
1448                         tsdField.TargetObject = parentField;
1449                         tsdField.FieldName = "TemplateSourceDirectory";
1450
1451                         CodeMethodReturnStatement parentRet = new CodeMethodReturnStatement (tsdField);
1452                         CodeConditionStatement condStatement = new CodeConditionStatement (
1453                                 new CodeBinaryOperatorExpression (parentField,
1454                                                                   CodeBinaryOperatorType.IdentityInequality,
1455                                                                   new CodePrimitiveExpression (null)),
1456                                 parentRet);
1457                         
1458                         prop.GetStatements.Add (condStatement);
1459                         
1460                         string tsd, bvd = parser.BaseVirtualDir;
1461                         int len = bvd.Length;
1462                         if (len >= 2 && bvd [0] == '~') {
1463                                 if (bvd [1] == '/')
1464                                     tsd = bvd.Substring (1);
1465                                 else
1466                                     tsd = '/' + bvd.Substring (1);
1467                         } else if (len >= 1 && bvd [0] != '/')
1468                                 tsd = '/' + bvd;
1469                         else
1470                                 tsd = bvd;
1471                         CodePrimitiveExpression expr = new CodePrimitiveExpression (tsd);
1472                         prop.GetStatements.Add (new CodeMethodReturnStatement (expr));
1473                         mainClass.Members.Add (prop);
1474                 }
1475
1476                 void CreateApplicationInstance ()
1477                 {
1478                         CodeMemberProperty prop = new CodeMemberProperty ();
1479                         Type appType = typeof (HttpApplication);
1480                         prop.Type = new CodeTypeReference (appType);
1481                         prop.Name = "ApplicationInstance";
1482                         prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
1483
1484                         CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
1485
1486                         propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
1487
1488                         CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
1489                         prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
1490 #if NET_2_0
1491                         if (partialClass != null)
1492                                 partialClass.Members.Add (prop);
1493                         else
1494 #endif
1495                         mainClass.Members.Add (prop);
1496                 }
1497
1498                 void CreateAutoHandlers ()
1499                 {
1500                         // Create AutoHandlers property
1501                         CodeMemberProperty prop = new CodeMemberProperty ();
1502                         prop.Type = new CodeTypeReference (typeof (int));
1503                         prop.Name = "AutoHandlers";
1504                         prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1505                         
1506                         CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
1507                         CodeFieldReferenceExpression fldRef ;
1508                         fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
1509                         ret.Expression = fldRef;
1510                         prop.GetStatements.Add (ret);
1511                         prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
1512
1513 #if NET_2_0
1514                         CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
1515                         prop.CustomAttributes.Add (attr);
1516 #endif
1517                         
1518                         mainClass.Members.Add (prop);
1519
1520                         // Add the __autoHandlers field
1521                         CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
1522                         fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
1523                         mainClass.Members.Add (fld);
1524                 }
1525
1526                 void CreateAutoEventWireup ()
1527                 {
1528                         // The getter returns false
1529                         CodeMemberProperty prop = new CodeMemberProperty ();
1530                         prop.Type = new CodeTypeReference (typeof (bool));
1531                         prop.Name = "SupportAutoEvents";
1532                         prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1533                         prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
1534                         mainClass.Members.Add (prop);
1535                 }
1536
1537 #if NET_2_0
1538                 protected virtual string HandleUrlProperty (string str, MemberInfo member)
1539                 {
1540                         return str;
1541                 }
1542 #endif
1543     
1544                 CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
1545                 {                       
1546 #if NET_2_0
1547                         bool wasNullable = false;
1548                         
1549                         if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
1550                                 Type[] types = type.GetGenericArguments();
1551                                 type = types[0]; // we're interested only in the first type here
1552                                 wasNullable = true;
1553                         }
1554 #endif
1555
1556                         if (type == typeof (string)) {
1557 #if NET_2_0
1558                                 object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
1559                                 if (urlAttr.Length != 0)
1560                                         str = HandleUrlProperty (str, member);
1561 #endif
1562                                 return new CodePrimitiveExpression (str);
1563                         }
1564
1565                         if (type == typeof (bool)) {
1566                                 if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
1567                                         return new CodePrimitiveExpression (true);
1568                                 else if (InvariantCompareNoCase (str, "false"))
1569                                         return new CodePrimitiveExpression (false);
1570 #if NET_2_0
1571                                 else if (wasNullable && InvariantCompareNoCase(str, "null"))
1572                                         return new CodePrimitiveExpression (null);
1573 #endif
1574                                 else
1575                                         throw new ParseException (currentLocation,
1576                                                         "Value '" + str  + "' is not a valid boolean.");
1577                         }
1578
1579                         if (str == null)
1580                                 return new CodePrimitiveExpression (null);
1581
1582                         if (type.IsPrimitive)
1583                                 return new CodePrimitiveExpression (Convert.ChangeType (str, type, CultureInfo.InvariantCulture));
1584
1585                         if (type == typeof (string [])) {
1586                                 string [] subs = str.Split (',');
1587                                 CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
1588                                 expr.CreateType = new CodeTypeReference (typeof (string));
1589                                 foreach (string v in subs) {
1590                                         expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
1591                                 }
1592
1593                                 return expr;
1594                         }
1595
1596                         if (type == typeof (Color)){
1597                                 if (colorConverter == null)
1598                                         colorConverter = TypeDescriptor.GetConverter (typeof (Color));
1599
1600                                 if (str.Trim().Length == 0) {
1601                                         CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
1602                                         return new CodeFieldReferenceExpression (ft, "Empty");
1603                                 }
1604                                 
1605                                 Color c;
1606                                 try {
1607                                         if (str.IndexOf (',') == -1) {
1608                                                 c = (Color) colorConverter.ConvertFromString (str);
1609                                         } else {
1610                                                 int [] argb = new int [4];
1611                                                 argb [0] = 255;
1612
1613                                                 string [] parts = str.Split (',');
1614                                                 int length = parts.Length;
1615                                                 if (length < 3)
1616                                                         throw new Exception ();
1617
1618                                                 int basei = (length == 4) ? 0 : 1;
1619                                                 for (int i = length - 1; i >= 0; i--) {
1620                                                         argb [basei + i] = (int) Byte.Parse (parts [i]);
1621                                                 }
1622                                                 c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
1623                                         }
1624                                 } catch (Exception e){
1625                                         // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
1626                                         // TypeConverter for Color fails to ConvertFromString.
1627                                         // Hence this hack...
1628                                         if (InvariantCompareNoCase ("LightGrey", str)) {
1629                                                 c = Color.LightGray;
1630                                         } else {
1631                                                 throw new ParseException (currentLocation,
1632                                                         "Color " + str + " is not a valid color.", e);
1633                                         }
1634                                 }
1635
1636                                 if (c.IsKnownColor){
1637                                         CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
1638                                         if (c.IsSystemColor)
1639                                                 type = typeof (SystemColors);
1640
1641                                         expr.TargetObject = new CodeTypeReferenceExpression (type);
1642                                         expr.FieldName = c.Name;
1643                                         return expr;
1644                                 } else {
1645                                         CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1646                                         m.TargetObject = new CodeTypeReferenceExpression (type);
1647                                         m.MethodName = "FromArgb";
1648                                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1649                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
1650                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
1651                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
1652                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
1653                                         return invoke;
1654                                 }
1655                         }
1656
1657                         TypeConverter converter = TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
1658                         
1659                         if (converter != null && converter.CanConvertFrom (typeof (string))) {
1660                                 object value = converter.ConvertFromInvariantString (str);
1661
1662                                 if (converter.CanConvertTo (typeof (InstanceDescriptor))) {
1663                                         InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1664                                         return GenerateInstance (idesc, true);
1665                                 }
1666
1667                                 CodeExpression exp = GenerateObjectInstance (value, false);
1668                                 if (exp != null) return exp;
1669                                 
1670                                 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1671                                 m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
1672                                 m.MethodName = "GetConverter";
1673                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1674                                 CodeTypeReference tref = new CodeTypeReference (type);
1675                                 invoke.Parameters.Add (new CodeTypeOfExpression (tref));
1676                                 
1677                                 invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
1678                                 invoke.Parameters.Add (new CodePrimitiveExpression (str));
1679
1680                                 return new CodeCastExpression (tref, invoke);
1681                         }
1682                         
1683                         Console.WriteLine ("Unknown type: " + type + " value: " + str);
1684
1685                         return new CodePrimitiveExpression (str);
1686                 }
1687                 
1688                 CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
1689                 {
1690                         CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
1691                         int n = 0;
1692                         foreach (object ob in idesc.Arguments) {
1693                                 CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
1694                                 if (exp == null) return null;
1695                                 parameters [n++] = exp;
1696                         }
1697                         
1698                         switch (idesc.MemberInfo.MemberType) {
1699                         case MemberTypes.Constructor:
1700                                 CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
1701                                 return new CodeObjectCreateExpression (tob, parameters);
1702
1703                         case MemberTypes.Method:
1704                                 CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1705                                 return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
1706
1707                         case MemberTypes.Field:
1708                                 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1709                                 return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
1710
1711                         case MemberTypes.Property:
1712                                 CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1713                                 return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
1714                         }
1715                         throw new ParseException (currentLocation, "Invalid instance type.");
1716                 }
1717                 
1718                 CodeExpression GenerateObjectInstance (object value, bool throwOnError)
1719                 {
1720                         if (value == null)
1721                                 return new CodePrimitiveExpression (null);
1722                         
1723                         Type t = value.GetType();
1724                         if (t.IsPrimitive || value is string)
1725                                 return new CodePrimitiveExpression (value);
1726                                 
1727                         if (t.IsArray) {
1728                                 Array ar = (Array) value;
1729                                 CodeExpression[] items = new CodeExpression [ar.Length];
1730                                 for (int n=0; n<ar.Length; n++) {
1731                                         CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
1732                                         if (exp == null) return null; 
1733                                         items [n] = exp;
1734                                 }
1735                                 return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
1736                         }
1737                         
1738                         TypeConverter converter = TypeDescriptor.GetConverter (t);
1739                         if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
1740                                 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1741                                 return GenerateInstance (idesc, throwOnError);
1742                         }
1743                         
1744                         InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
1745                         if (desc != null) return GenerateInstance (desc, throwOnError);
1746                         
1747                         if (throwOnError)
1748                                 throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
1749                         else
1750                                 return null;
1751                 }
1752                 
1753                 InstanceDescriptor GetDefaultInstanceDescriptor (object value)
1754                 {
1755                         if (value is System.Web.UI.WebControls.Unit) {
1756                                 System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
1757                                 ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
1758                                         BindingFlags.Instance | BindingFlags.Public,
1759                                         null,
1760                                         new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
1761                                         null);
1762                                 
1763                                 return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
1764                         }
1765                         
1766                         if (value is System.Web.UI.WebControls.FontUnit) {
1767                                 System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
1768                                 ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
1769                                         BindingFlags.Instance | BindingFlags.Public,
1770                                         null,
1771                                         new Type[] {typeof(System.Web.UI.WebControls.Unit)},
1772                                         null);
1773                                 return new InstanceDescriptor (c, new object[] {s.Unit});
1774                         }
1775                         return null;
1776                 }
1777         }
1778 }
1779
1780
1781