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