forgotten ifdefs
[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);
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")) {
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 (new CodeThisReferenceExpression (), "Page");
447                                 CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
448                                 CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
449                                 CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
450                                 method.Statements.Add (ccs);
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")) {
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                         // FIXME: create and pass an instance of BoundPropertyEntry
694                         CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
695                         convert.Method = new CodeMethodReferenceExpression (
696                                 new CodeTypeReferenceExpression (typeof(Convert)),
697                                 "ToString");
698                         convert.Parameters.Add (eb.GetCodeExpression (null, parsedData, ctx));
699                         convert.Parameters.Add (
700                                 new CodeFieldReferenceExpression (
701                                         new CodeTypeReferenceExpression ("System.Globalization.CultureInfo"),
702                                         "CurrentCulture"));
703                         assign.Right = convert;
704                         
705                         method.Statements.Add (assign);
706                 }
707
708                 void AssignPropertyFromResources (CodeMemberMethod method, MemberInfo mi, string attvalue)
709                 {
710                         string resname = String.Format ("{0}.{1}", attvalue, mi.Name);
711                         bool isProperty = mi.MemberType == MemberTypes.Property;
712                         bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);
713
714                         if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
715                                 return;
716                         
717                         Type member_type = null;
718                         if (isProperty) {
719                                 PropertyInfo pi = mi as PropertyInfo;
720                                 member_type = pi.PropertyType;
721                         } else if (isField) { 
722                                 FieldInfo fi = mi as FieldInfo;
723                                 member_type = fi.FieldType;
724                         } else // should never happen
725                                 return;
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                         CodeAssignStatement assign = new CodeAssignStatement ();
741                         assign.Left = new CodePropertyReferenceExpression (ctrlVar, mi.Name);
742                         CodeMethodInvokeExpression getlro = new CodeMethodInvokeExpression (
743                                 new CodeThisReferenceExpression (),
744                                 "GetLocalResourceObject",
745                                 new CodeExpression [] { new CodePrimitiveExpression (resname) });
746                         
747                         CodeMethodInvokeExpression convert = new CodeMethodInvokeExpression ();
748                         convert.Method = new CodeMethodReferenceExpression (
749                                 new CodeTypeReferenceExpression (typeof(System.Convert)),
750                                 "ToString");
751                         convert.Parameters.Add (getlro);
752                         assign.Right = convert;                 
753
754                         method.Statements.Add (assign);
755                 }
756
757                 void AssignPropertiesFromResources (CodeMemberMethod method, Type controlType, string attvalue)
758                 {
759                         // Process all public fields and properties of the control. We don't use GetMembers to make the code
760                         // faster
761                         FieldInfo [] fields = controlType.GetFields (
762                                 BindingFlags.Instance | BindingFlags.Static |
763                                 BindingFlags.Public | BindingFlags.FlattenHierarchy);
764                         PropertyInfo [] properties = controlType.GetProperties (
765                                 BindingFlags.Instance | BindingFlags.Static |
766                                 BindingFlags.Public | BindingFlags.FlattenHierarchy);
767
768                         foreach (FieldInfo fi in fields)
769                                 AssignPropertyFromResources (method, fi, attvalue);
770                         foreach (PropertyInfo pi in properties)
771                                 AssignPropertyFromResources (method, pi, attvalue);
772                 }
773                 
774                 void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
775                 {
776                         if (attvalue == null || attvalue.Length == 0)
777                                 return;
778                         
779                         Type controlType = builder.ControlType;
780                         if (controlType == null)
781                                 return;
782
783                         AssignPropertiesFromResources (builder.method, controlType, attvalue);
784                 }
785 #endif
786                 
787                 void AddEventAssign (CodeMemberMethod method, string name, Type type, string value)
788                 {
789                         //"__ctrl.{0} += new {1} (this.{2});"
790                         CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);
791
792                         CodeDelegateCreateExpression create;
793                         create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);
794
795                         CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
796                         method.Statements.Add (attach);
797                 }
798                 
799                 void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
800                 {
801                         EventInfo [] ev_info = null;
802                         Type type = builder.ControlType;
803                         
804                         string attvalue = builder.attribs [id] as string;
805                         if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
806                                 if (ev_info == null)
807                                         ev_info = type.GetEvents ();
808
809                                 string id_as_event = id.Substring (2);
810                                 foreach (EventInfo ev in ev_info){
811                                         if (InvariantCompareNoCase (ev.Name, id_as_event)){
812                                                 AddEventAssign (builder.method,
813                                                                 ev.Name,
814                                                                 ev.EventHandlerType,
815                                                                 attvalue);
816                                                 
817                                                 return;
818                                         }
819                                 }
820
821                         }
822
823 #if NET_2_0
824                         if (id.ToLower () == "meta:resourcekey") {
825                                 AssignPropertiesFromResources (builder, attvalue);
826                                 return;
827                         }
828 #endif
829                         
830                         int hyphen = id.IndexOf ('-');
831                         string alt_id = id;
832                         if (hyphen != -1)
833                                 alt_id = id.Substring (0, hyphen);
834
835                         MemberInfo fop = GetFieldOrProperty (type, alt_id);
836                         if (fop != null) {
837                                 if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
838                                         return;
839                         }
840
841                         if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
842                                 throw new ParseException (builder.location, "Unrecognized attribute: " + id);
843
844                         string val;
845                         CodeMemberMethod method = builder.method;
846                         bool databound = IsDataBound (attvalue);
847
848                         if (databound) {
849                                 val = attvalue.Substring (3);
850                                 val = val.Substring (0, val.Length - 2);
851                                 CreateDBAttributeMethod (builder, id, val);
852                         } else {
853                                 CodeCastExpression cast;
854                                 CodeMethodReferenceExpression methodExpr;
855                                 CodeMethodInvokeExpression expr;
856
857                                 cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
858                                 methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
859                                 expr = new CodeMethodInvokeExpression (methodExpr);
860                                 expr.Parameters.Add (new CodePrimitiveExpression (id));
861                                 expr.Parameters.Add (new CodePrimitiveExpression (attvalue));
862                                 method.Statements.Add (expr);
863                         }
864
865                 }
866
867                 protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
868                 {
869 #if NET_2_0
870                         bool haveMetaKey = false;
871 #endif
872                         this.dataBoundAtts = 0;
873                         IDictionary atts = builder.attribs;
874                         if (atts == null || atts.Count == 0)
875                                 return;
876                         
877                         foreach (string id in atts.Keys) {
878                                 if (InvariantCompareNoCase (id, "runat"))
879                                         continue;
880
881 #if NET_2_0
882                                 /* we skip SkinID here as it's assigned in BuildControlTree */
883                                 if (InvariantCompareNoCase (id, "skinid"))
884                                         continue;
885                                 if (InvariantCompareNoCase (id, "meta:resourcekey")) {
886                                         haveMetaKey = true;
887                                         continue;
888                                 }
889 #endif
890                                 CreateAssignStatementFromAttribute (builder, id);
891                         }
892                         
893 #if NET_2_0
894                         if (haveMetaKey)
895                                 CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
896 #endif
897                 }
898
899                 void CreateDBAttributeMethod (ControlBuilder builder, string attr, string code)
900                 {
901                         if (code == null || code.Trim () == "")
902                                 return;
903
904                         string id = builder.GetNextID (null);
905                         string dbMethodName = "__DataBind_" + id;
906                         CodeMemberMethod method = builder.method;
907                         AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
908
909                         method = CreateDBMethod (dbMethodName, GetContainerType (builder), builder.ControlType);
910                         CodeCastExpression cast;
911                         CodeMethodReferenceExpression methodExpr;
912                         CodeMethodInvokeExpression expr;
913
914                         CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
915                         cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
916                         methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
917                         expr = new CodeMethodInvokeExpression (methodExpr);
918                         expr.Parameters.Add (new CodePrimitiveExpression (attr));
919                         CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
920                         tostring.Method = new CodeMethodReferenceExpression (
921                                                         new CodeTypeReferenceExpression (typeof (Convert)),
922                                                         "ToString");
923                         tostring.Parameters.Add (new CodeSnippetExpression (code));
924                         expr.Parameters.Add (tostring);
925                         method.Statements.Add (expr);
926                         mainClass.Members.Add (method);
927                 }
928
929                 void AddRenderControl (ControlBuilder builder)
930                 {
931                         CodeIndexerExpression indexer = new CodeIndexerExpression ();
932                         indexer.TargetObject = new CodePropertyReferenceExpression (
933                                                         new CodeArgumentReferenceExpression ("parameterContainer"),
934                                                         "Controls");
935                                                         
936                         indexer.Indices.Add (new CodePrimitiveExpression (builder.renderIndex));
937                         
938                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
939                         invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
940                         builder.renderMethod.Statements.Add (invoke);
941                         builder.renderIndex++;
942                 }
943
944                 protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
945                 {
946                         if (parent == null || child == null)
947                                 return;
948                         CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.method.Name);
949                         CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);
950
951                         object [] atts = null;
952                         
953                         if (child.ControlType != null)
954                                 child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
955                         if (atts != null && atts.Length > 0) {
956                                 PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
957                                 CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
958                                 CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
959                                 build.Parameters.Add (new CodeArgumentReferenceExpression("__ctrl"));
960                                 build.Parameters.Add (new CodePrimitiveExpression (child.ID));
961 #if NET_1_1
962                                 if (pca.Shared)
963                                         build.Parameters.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
964                                 else
965 #endif
966                                         build.Parameters.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
967                                         
968                                 build.Parameters.Add (new CodePrimitiveExpression (pca.Duration));
969                                 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByParams));
970                                 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByControls));
971                                 build.Parameters.Add (new CodePrimitiveExpression (pca.VaryByCustom));
972                                 build.Parameters.Add (new CodeDelegateCreateExpression (
973                                                               new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
974                                                               thisRef, child.method.Name));
975                                 
976                                 parent.methodStatements.Add (build);
977                                 if (parent.HasAspCode)
978                                         AddRenderControl (parent);
979                                 return;
980                         }
981                                 
982                         if (child.isProperty || parent.ChildrenAsProperties) {
983                                 expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
984                                 parent.methodStatements.Add (expr);
985                                 return;
986                         }
987
988                         parent.methodStatements.Add (expr);
989                         CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
990                         if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType)) {
991                                 AddParsedSubObjectStmt (parent, field);
992                         } else {
993                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
994                                 invoke.Parameters.Add (field);
995                                 parent.methodStatements.Add (invoke);
996                         }
997                                 
998                         if (parent.HasAspCode)
999                                 AddRenderControl (parent);
1000                 }
1001
1002                 void AddTemplateInvocation (CodeMemberMethod method, string name, string methodName)
1003                 {
1004                         CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1005
1006                         CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1007                         newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1008
1009                         CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1010                         newCompiled.Parameters.Add (newBuild);
1011
1012                         CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1013                         method.Statements.Add (assign);
1014                 }
1015
1016 #if NET_2_0
1017                 void AddBindableTemplateInvocation (CodeMemberMethod method, string name, string methodName, string extractMethodName)
1018                 {
1019                         CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);
1020
1021                         CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1022                         newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1023
1024                         CodeObjectCreateExpression newExtract = new CodeObjectCreateExpression (typeof (ExtractTemplateValuesMethod));
1025                         newExtract.Parameters.Add (new CodeMethodReferenceExpression (thisRef, extractMethodName));
1026
1027                         CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
1028                         newCompiled.Parameters.Add (newBuild);
1029                         newCompiled.Parameters.Add (newExtract);
1030                         
1031                         CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
1032                         method.Statements.Add (assign);
1033                 }
1034                 
1035                 string CreateExtractValuesMethod (TemplateBuilder builder)
1036                 {
1037                         CodeMemberMethod method = new CodeMemberMethod ();
1038                         method.Name = "__ExtractValues_" + builder.ID;
1039                         method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
1040                         method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
1041                         
1042                         CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
1043                         arg.Type = new CodeTypeReference (typeof (Control));
1044                         arg.Name = "__container";
1045                         method.Parameters.Add (arg);
1046                         mainClass.Members.Add (method);
1047                         
1048                         CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
1049                         newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
1050                         method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
1051                         CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
1052                         
1053                         if (builder.Bindings != null) {
1054                                 Hashtable hash = new Hashtable ();
1055                                 foreach (TemplateBinding binding in builder.Bindings) {
1056                                         CodeConditionStatement sif;
1057                                         CodeVariableReferenceExpression control;
1058                                         CodeAssignStatement assign;
1059
1060                                         if (hash [binding.ControlId] == null) {
1061
1062                                                 CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
1063                                                 method.Statements.Add (dec);
1064                                                 CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
1065                                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
1066                                                 invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));
1067
1068                                                 assign = new CodeAssignStatement ();
1069                                                 control = new CodeVariableReferenceExpression (binding.ControlId);
1070                                                 assign.Left = control;
1071                                                 assign.Right = new CodeCastExpression (binding.ControlType, invoke);
1072                                                 method.Statements.Add (assign);
1073
1074                                                 sif = new CodeConditionStatement ();
1075                                                 sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
1076
1077                                                 method.Statements.Add (sif);
1078
1079                                                 hash [binding.ControlId] = sif;
1080                                         }
1081
1082                                         sif = (CodeConditionStatement) hash [binding.ControlId];
1083                                         control = new CodeVariableReferenceExpression (binding.ControlId);
1084                                         assign = new CodeAssignStatement ();
1085                                         assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
1086                                         assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
1087                                         sif.TrueStatements.Add (assign);
1088                                 }
1089                         }
1090
1091                         method.Statements.Add (new CodeMethodReturnStatement (tableExp));
1092                         return method.Name;
1093                 }
1094
1095                 void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
1096                 {
1097                         CodeObjectCreateExpression newBuild = new CodeObjectCreateExpression (typeof (BuildTemplateMethod));
1098                         newBuild.Parameters.Add (new CodeMethodReferenceExpression (thisRef, methodName));
1099
1100                         CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
1101                         newCompiled.Parameters.Add (newBuild);
1102                         
1103                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
1104                         invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
1105                         invoke.Parameters.Add (newCompiled);
1106
1107                         method.Statements.Add (invoke);
1108                 }
1109 #endif
1110
1111                 void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
1112                 {
1113                         if (cr.Code == null || cr.Code.Trim () == "")
1114                                 return;
1115
1116                         if (!cr.IsAssign) {
1117                                 CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
1118                                 parent.renderMethod.Statements.Add (code);
1119                                 return;
1120                         }
1121
1122                         CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
1123                         expr.Method = new CodeMethodReferenceExpression (
1124                                                         new CodeArgumentReferenceExpression ("__output"),
1125                                                         "Write");
1126
1127                         expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
1128                         parent.renderMethod.Statements.Add (expr);
1129                 }
1130
1131                 static Type GetContainerType (ControlBuilder builder)
1132                 {
1133                         TemplateBuilder tb = builder as TemplateBuilder;
1134                         if (tb != null && tb.ContainerType != null)
1135                                 return tb.ContainerType;
1136
1137                         Type type = builder.BindingContainerType;
1138
1139                         PropertyInfo prop = type.GetProperty ("Items", noCaseFlags & ~BindingFlags.NonPublic);
1140                         if (prop == null)
1141                                 return type;
1142
1143                         Type ptype = prop.PropertyType;
1144                         if (!typeof (ICollection).IsAssignableFrom (ptype))
1145                                 return type;
1146
1147                         prop = ptype.GetProperty ("Item", noCaseFlags & ~BindingFlags.NonPublic);
1148                         if (prop == null)
1149                                 return type;
1150
1151                         return prop.PropertyType;
1152                 }
1153                 
1154                 CodeMemberMethod CreateDBMethod (string name, Type container, Type target)
1155                 {
1156                         CodeMemberMethod method = new CodeMemberMethod ();
1157                         method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
1158                         method.Name = name;
1159                         method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
1160                         method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
1161
1162                         CodeTypeReference containerRef = new CodeTypeReference (container);
1163                         CodeTypeReference targetRef = new CodeTypeReference (target);
1164
1165                         CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
1166                         decl.Name = "Container";
1167                         decl.Type = containerRef;
1168                         method.Statements.Add (decl);
1169
1170                         decl = new CodeVariableDeclarationStatement();
1171                         decl.Name = "target";
1172                         decl.Type = targetRef;
1173                         method.Statements.Add (decl);
1174
1175                         CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1176                         CodeAssignStatement assign = new CodeAssignStatement ();
1177                         assign.Left = targetExpr;
1178                         assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
1179                         method.Statements.Add (assign);
1180
1181                         assign = new CodeAssignStatement ();
1182                         assign.Left = new CodeVariableReferenceExpression ("Container");
1183                         assign.Right = new CodeCastExpression (containerRef,
1184                                                 new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
1185                         method.Statements.Add (assign);
1186
1187                         return method;
1188                 }
1189
1190                 void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
1191                 {
1192                         if (db.Code == null || db.Code.Trim () == "")
1193                                 return;
1194
1195                         EnsureID (db);
1196                         CreateField (db, false);
1197
1198                         string dbMethodName = "__DataBind_" + db.ID;
1199                         // Add the method that builds the DataBoundLiteralControl
1200                         InitMethod (db, false, false);
1201                         CodeMemberMethod method = db.method;
1202                         AddEventAssign (method, "DataBinding", typeof (EventHandler), dbMethodName);
1203                         method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1204
1205                         // Add the DataBind handler
1206                         method = CreateDBMethod (dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
1207
1208                         CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
1209                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1210                         invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
1211                         invoke.Parameters.Add (new CodePrimitiveExpression (0));
1212
1213                         CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
1214                         tostring.Method = new CodeMethodReferenceExpression (
1215                                                         new CodeTypeReferenceExpression (typeof (Convert)),
1216                                                         "ToString");
1217                         tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
1218                         invoke.Parameters.Add (tostring);
1219                         method.Statements.Add (invoke);
1220                         
1221                         mainClass.Members.Add (method);
1222
1223                         AddChildCall (builder, db);
1224                 }
1225
1226                 void FlushText (ControlBuilder builder, StringBuilder sb)
1227                 {
1228                         if (sb.Length > 0) {
1229                                 AddLiteralSubObject (builder, sb.ToString ());
1230                                 sb.Length = 0;
1231                         }
1232                 }
1233
1234                 protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
1235                 {
1236                         EnsureID (builder);
1237                         bool isTemplate = (typeof (TemplateBuilder).IsAssignableFrom (builder.GetType ()));
1238                         if (!isTemplate && !inTemplate) {
1239                                 CreateField (builder, true);
1240                         } else if (!isTemplate) {
1241                                 builder.ID = builder.GetNextID (null);
1242                                 CreateField (builder, false);
1243                         }
1244
1245                         InitMethod (builder, isTemplate, childrenAsProperties);
1246                         if (!isTemplate || builder.GetType () == typeof (RootBuilder))
1247                                 CreateAssignStatementsFromAttributes (builder);
1248
1249                         if (builder.Children != null && builder.Children.Count > 0) {
1250                                 ArrayList templates = null;
1251
1252                                 StringBuilder sb = new StringBuilder ();
1253                                 foreach (object b in builder.Children) {
1254
1255                                         if (b is string) {
1256                                                 sb.Append ((string) b);
1257                                                 continue;
1258                                         }
1259
1260                                         FlushText (builder, sb);
1261                                         if (b is ObjectTagBuilder) {
1262                                                 ProcessObjectTag ((ObjectTagBuilder) b);
1263                                                 continue;
1264                                         }
1265
1266                                         StringPropertyBuilder pb = b as StringPropertyBuilder;
1267                                         if (pb != null){
1268                                                 if (pb.Children != null && pb.Children.Count > 0) {
1269                                                         StringBuilder asb = new StringBuilder ();
1270                                                         foreach (string s in pb.Children)
1271                                                                 asb.Append (s);
1272                                                         CodeMemberMethod method = builder.method;
1273                                                         CodeAssignStatement assign = new CodeAssignStatement ();
1274                                                         assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
1275                                                         assign.Right = new CodePrimitiveExpression (asb.ToString ());
1276                                                         method.Statements.Add (assign);
1277                                                 }
1278                                                 continue;
1279                                         }
1280
1281 #if NET_2_0
1282                                         if (b is ContentBuilderInternal) {
1283                                                 ContentBuilderInternal cb = (ContentBuilderInternal) b;
1284                                                 CreateControlTree (cb, false, true);
1285                                                 AddContentTemplateInvocation (cb, builder.method, cb.method.Name);
1286                                                 continue;
1287                                         }
1288 #endif
1289
1290                                         if (b is TemplateBuilder) {
1291                                                 if (templates == null)
1292                                                         templates = new ArrayList ();
1293
1294                                                 templates.Add (b);
1295                                                 continue;
1296                                         }
1297
1298                                         if (b is CodeRenderBuilder) {
1299                                                 AddCodeRender (builder, (CodeRenderBuilder) b);
1300                                                 continue;
1301                                         }
1302
1303                                         if (b is DataBindingBuilder) {
1304                                                 AddDataBindingLiteral (builder, (DataBindingBuilder) b);
1305                                                 continue;
1306                                         }
1307                                         
1308                                         if (b is ControlBuilder) {
1309                                                 ControlBuilder child = (ControlBuilder) b;
1310                                                 CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
1311                                                 AddChildCall (builder, child);
1312                                                 continue;
1313                                         }
1314
1315                                         throw new Exception ("???");
1316                                 }
1317
1318                                 FlushText (builder, sb);
1319
1320                                 if (templates != null) {
1321                                         foreach (TemplateBuilder b in templates) {
1322                                                 CreateControlTree (b, true, false);
1323 #if NET_2_0
1324                                                 if (b.BindingDirection == BindingDirection.TwoWay) {
1325                                                         string extractMethod = CreateExtractValuesMethod (b);
1326                                                         AddBindableTemplateInvocation (builder.method, b.TagName, b.method.Name, extractMethod);
1327                                                 }
1328                                                 else
1329 #endif
1330                                                 AddTemplateInvocation (builder.method, b.TagName, b.method.Name);
1331                                         }
1332                                 }
1333
1334                         }
1335
1336                         if (builder.defaultPropertyBuilder != null) {
1337                                 ControlBuilder b = builder.defaultPropertyBuilder;
1338                                 CreateControlTree (b, false, true);
1339                                 AddChildCall (builder, b);
1340                         }
1341
1342                         if (builder.HasAspCode) {
1343                                 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1344                                 m.TargetObject = thisRef;
1345                                 m.MethodName = builder.renderMethod.Name;
1346
1347                                 CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
1348                                 create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
1349                                 create.TargetObject = thisRef;
1350                                 create.MethodName = builder.renderMethod.Name;
1351
1352                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
1353                                 invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
1354                                 invoke.Parameters.Add (create);
1355
1356                                 builder.methodStatements.Add (invoke);
1357                         }
1358                         
1359                         if (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType))
1360                                 builder.method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));
1361
1362 #if NET_2_0
1363                         if (builder is RootBuilder)
1364                                 if (!String.IsNullOrEmpty (parser.MetaResourceKey))
1365                                         AssignPropertiesFromResources (builder.method, parser.BaseType, parser.MetaResourceKey);
1366 #endif
1367                 }
1368                 
1369                 protected internal override void CreateMethods ()
1370                 {
1371                         base.CreateMethods ();
1372
1373                         CreateProperties ();
1374                         CreateControlTree (parser.RootBuilder, false, false);
1375                         CreateFrameworkInitializeMethod ();
1376                 }
1377
1378                 void CallBaseFrameworkInitialize (CodeMemberMethod method)
1379                 {
1380                         CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
1381                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
1382                         method.Statements.Add (invoke);
1383                 }
1384
1385                 void CreateFrameworkInitializeMethod ()
1386                 {
1387                         CodeMemberMethod method = new CodeMemberMethod ();
1388                         method.Name = "FrameworkInitialize";
1389                         method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1390                         PrependStatementsToFrameworkInitialize (method);
1391                         CallBaseFrameworkInitialize (method);
1392                         AppendStatementsToFrameworkInitialize (method);
1393                         mainClass.Members.Add (method);
1394                 }
1395
1396                 protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
1397                 {
1398                 }
1399
1400                 protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
1401                 {
1402                         if (!parser.EnableViewState) {
1403                                 CodeAssignStatement stmt = new CodeAssignStatement ();
1404                                 stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
1405                                 stmt.Right = new CodePrimitiveExpression (false);
1406                                 method.Statements.Add (stmt);
1407                         }
1408
1409                         CodeMethodReferenceExpression methodExpr;
1410                         methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
1411                         CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
1412                         method.Statements.Add (new CodeExpressionStatement (expr));
1413                 }
1414
1415                 protected override void AddApplicationAndSessionObjects ()
1416                 {
1417                         foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
1418                                 CreateFieldForObject (tag.Type, tag.ObjectID);
1419                                 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
1420                         }
1421
1422                         foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
1423                                 CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
1424                         }
1425                 }
1426
1427                 protected void ProcessObjectTag (ObjectTagBuilder tag)
1428                 {
1429                         string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
1430                         CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
1431                 }
1432
1433                 void CreateProperties ()
1434                 {
1435                         if (!parser.AutoEventWireup) {
1436                                 CreateAutoEventWireup ();
1437                         } else {
1438                                 CreateAutoHandlers ();
1439                         }
1440
1441                         CreateApplicationInstance ();
1442                         CreateTemplateSourceDirectory ();
1443                 }
1444
1445                 void CreateTemplateSourceDirectory ()
1446                 {
1447                         CodeMemberProperty prop = new CodeMemberProperty ();
1448                         prop.Type = new CodeTypeReference (typeof (string));
1449                         prop.Name = "TemplateSourceDirectory";
1450                         prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
1451
1452 #if NET_2_0
1453                         if (!(parser is MasterPageParser)) {
1454 #endif
1455                                 // if ((this.Parent != null))
1456                                 //   return this.Parent.TemplateSourceDirectory;
1457                                 CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression ();
1458                                 parentField.TargetObject = thisRef;
1459                                 parentField.FieldName = "Parent";
1460                         
1461                                 CodeFieldReferenceExpression tsdField = new CodeFieldReferenceExpression ();
1462                                 tsdField.TargetObject = parentField;
1463                                 tsdField.FieldName = "TemplateSourceDirectory";
1464
1465                                 CodeMethodReturnStatement parentRet = new CodeMethodReturnStatement (tsdField);
1466                                 CodeConditionStatement condStatement = new CodeConditionStatement (
1467                                         new CodeBinaryOperatorExpression (parentField,
1468                                                                           CodeBinaryOperatorType.IdentityInequality,
1469                                                                           new CodePrimitiveExpression (null)),
1470                                         parentRet);
1471                         
1472                                 prop.GetStatements.Add (condStatement);
1473 #if NET_2_0
1474                         }
1475 #endif
1476
1477                         string tsd, bvd = parser.BaseVirtualDir;
1478                         int len = bvd.Length;
1479                         if (len >= 2 && bvd [0] == '~') {
1480                                 if (bvd [1] == '/')
1481                                     tsd = bvd.Substring (1);
1482                                 else
1483                                     tsd = '/' + bvd.Substring (1);
1484                         } else if (len >= 1 && bvd [0] != '/')
1485                                 tsd = '/' + bvd;
1486                         else
1487                                 tsd = bvd;
1488                         CodePrimitiveExpression expr = new CodePrimitiveExpression (tsd);
1489                         prop.GetStatements.Add (new CodeMethodReturnStatement (expr));
1490                         mainClass.Members.Add (prop);
1491                 }
1492
1493                 void CreateApplicationInstance ()
1494                 {
1495                         CodeMemberProperty prop = new CodeMemberProperty ();
1496                         Type appType = typeof (HttpApplication);
1497                         prop.Type = new CodeTypeReference (appType);
1498                         prop.Name = "ApplicationInstance";
1499                         prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;
1500
1501                         CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");
1502
1503                         propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");
1504
1505                         CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
1506                         prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
1507 #if NET_2_0
1508                         if (partialClass != null)
1509                                 partialClass.Members.Add (prop);
1510                         else
1511 #endif
1512                         mainClass.Members.Add (prop);
1513                 }
1514
1515                 void CreateAutoHandlers ()
1516                 {
1517                         // Create AutoHandlers property
1518                         CodeMemberProperty prop = new CodeMemberProperty ();
1519                         prop.Type = new CodeTypeReference (typeof (int));
1520                         prop.Name = "AutoHandlers";
1521                         prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1522                         
1523                         CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
1524                         CodeFieldReferenceExpression fldRef ;
1525                         fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
1526                         ret.Expression = fldRef;
1527                         prop.GetStatements.Add (ret);
1528                         prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));
1529
1530 #if NET_2_0
1531                         CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
1532                         prop.CustomAttributes.Add (attr);
1533 #endif
1534                         
1535                         mainClass.Members.Add (prop);
1536
1537                         // Add the __autoHandlers field
1538                         CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
1539                         fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
1540                         mainClass.Members.Add (fld);
1541                 }
1542
1543                 void CreateAutoEventWireup ()
1544                 {
1545                         // The getter returns false
1546                         CodeMemberProperty prop = new CodeMemberProperty ();
1547                         prop.Type = new CodeTypeReference (typeof (bool));
1548                         prop.Name = "SupportAutoEvents";
1549                         prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
1550                         prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
1551                         mainClass.Members.Add (prop);
1552                 }
1553
1554 #if NET_2_0
1555                 protected virtual string HandleUrlProperty (string str, MemberInfo member)
1556                 {
1557                         return str;
1558                 }
1559 #endif
1560     
1561                 CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
1562                 {                       
1563 #if NET_2_0
1564                         bool wasNullable = false;
1565                         
1566                         if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
1567                                 Type[] types = type.GetGenericArguments();
1568                                 type = types[0]; // we're interested only in the first type here
1569                                 wasNullable = true;
1570                         }
1571 #endif
1572
1573                         if (type == typeof (string)) {
1574 #if NET_2_0
1575                                 object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
1576                                 if (urlAttr.Length != 0)
1577                                         str = HandleUrlProperty (str, member);
1578 #endif
1579                                 return new CodePrimitiveExpression (str);
1580                         }
1581
1582                         if (type == typeof (bool)) {
1583                                 if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
1584                                         return new CodePrimitiveExpression (true);
1585                                 else if (InvariantCompareNoCase (str, "false"))
1586                                         return new CodePrimitiveExpression (false);
1587 #if NET_2_0
1588                                 else if (wasNullable && InvariantCompareNoCase(str, "null"))
1589                                         return new CodePrimitiveExpression (null);
1590 #endif
1591                                 else
1592                                         throw new ParseException (currentLocation,
1593                                                         "Value '" + str  + "' is not a valid boolean.");
1594                         }
1595
1596                         if (str == null)
1597                                 return new CodePrimitiveExpression (null);
1598
1599                         if (type.IsPrimitive)
1600                                 return new CodePrimitiveExpression (Convert.ChangeType (str, type, CultureInfo.InvariantCulture));
1601
1602                         if (type == typeof (string [])) {
1603                                 string [] subs = str.Split (',');
1604                                 CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
1605                                 expr.CreateType = new CodeTypeReference (typeof (string));
1606                                 foreach (string v in subs) {
1607                                         expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));
1608                                 }
1609
1610                                 return expr;
1611                         }
1612
1613                         if (type == typeof (Color)){
1614                                 if (colorConverter == null)
1615                                         colorConverter = TypeDescriptor.GetConverter (typeof (Color));
1616
1617                                 if (str.Trim().Length == 0) {
1618                                         CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
1619                                         return new CodeFieldReferenceExpression (ft, "Empty");
1620                                 }
1621                                 
1622                                 Color c;
1623                                 try {
1624                                         if (str.IndexOf (',') == -1) {
1625                                                 c = (Color) colorConverter.ConvertFromString (str);
1626                                         } else {
1627                                                 int [] argb = new int [4];
1628                                                 argb [0] = 255;
1629
1630                                                 string [] parts = str.Split (',');
1631                                                 int length = parts.Length;
1632                                                 if (length < 3)
1633                                                         throw new Exception ();
1634
1635                                                 int basei = (length == 4) ? 0 : 1;
1636                                                 for (int i = length - 1; i >= 0; i--) {
1637                                                         argb [basei + i] = (int) Byte.Parse (parts [i]);
1638                                                 }
1639                                                 c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
1640                                         }
1641                                 } catch (Exception e){
1642                                         // Hack: "LightGrey" is accepted, but only for ASP.NET, as the
1643                                         // TypeConverter for Color fails to ConvertFromString.
1644                                         // Hence this hack...
1645                                         if (InvariantCompareNoCase ("LightGrey", str)) {
1646                                                 c = Color.LightGray;
1647                                         } else {
1648                                                 throw new ParseException (currentLocation,
1649                                                         "Color " + str + " is not a valid color.", e);
1650                                         }
1651                                 }
1652
1653                                 if (c.IsKnownColor){
1654                                         CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
1655                                         if (c.IsSystemColor)
1656                                                 type = typeof (SystemColors);
1657
1658                                         expr.TargetObject = new CodeTypeReferenceExpression (type);
1659                                         expr.FieldName = c.Name;
1660                                         return expr;
1661                                 } else {
1662                                         CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1663                                         m.TargetObject = new CodeTypeReferenceExpression (type);
1664                                         m.MethodName = "FromArgb";
1665                                         CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1666                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
1667                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
1668                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
1669                                         invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
1670                                         return invoke;
1671                                 }
1672                         }
1673
1674                         TypeConverter converter = TypeDescriptor.GetProperties (member.DeclaringType) [member.Name].Converter;
1675                         
1676                         if (converter != null && converter.CanConvertFrom (typeof (string))) {
1677                                 object value = converter.ConvertFromInvariantString (str);
1678
1679                                 if (converter.CanConvertTo (typeof (InstanceDescriptor))) {
1680                                         InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1681                                         return GenerateInstance (idesc, true);
1682                                 }
1683
1684                                 CodeExpression exp = GenerateObjectInstance (value, false);
1685                                 if (exp != null) return exp;
1686                                 
1687                                 CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
1688                                 m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
1689                                 m.MethodName = "GetConverter";
1690                                 CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
1691                                 CodeTypeReference tref = new CodeTypeReference (type);
1692                                 invoke.Parameters.Add (new CodeTypeOfExpression (tref));
1693                                 
1694                                 invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
1695                                 invoke.Parameters.Add (new CodePrimitiveExpression (str));
1696
1697                                 return new CodeCastExpression (tref, invoke);
1698                         }
1699                         
1700                         Console.WriteLine ("Unknown type: " + type + " value: " + str);
1701
1702                         return new CodePrimitiveExpression (str);
1703                 }
1704                 
1705                 CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
1706                 {
1707                         CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
1708                         int n = 0;
1709                         foreach (object ob in idesc.Arguments) {
1710                                 CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
1711                                 if (exp == null) return null;
1712                                 parameters [n++] = exp;
1713                         }
1714                         
1715                         switch (idesc.MemberInfo.MemberType) {
1716                         case MemberTypes.Constructor:
1717                                 CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
1718                                 return new CodeObjectCreateExpression (tob, parameters);
1719
1720                         case MemberTypes.Method:
1721                                 CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1722                                 return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);
1723
1724                         case MemberTypes.Field:
1725                                 CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1726                                 return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);
1727
1728                         case MemberTypes.Property:
1729                                 CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
1730                                 return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
1731                         }
1732                         throw new ParseException (currentLocation, "Invalid instance type.");
1733                 }
1734                 
1735                 CodeExpression GenerateObjectInstance (object value, bool throwOnError)
1736                 {
1737                         if (value == null)
1738                                 return new CodePrimitiveExpression (null);
1739                         
1740                         Type t = value.GetType();
1741                         if (t.IsPrimitive || value is string)
1742                                 return new CodePrimitiveExpression (value);
1743                                 
1744                         if (t.IsArray) {
1745                                 Array ar = (Array) value;
1746                                 CodeExpression[] items = new CodeExpression [ar.Length];
1747                                 for (int n=0; n<ar.Length; n++) {
1748                                         CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
1749                                         if (exp == null) return null; 
1750                                         items [n] = exp;
1751                                 }
1752                                 return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
1753                         }
1754                         
1755                         TypeConverter converter = TypeDescriptor.GetConverter (t);
1756                         if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
1757                                 InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
1758                                 return GenerateInstance (idesc, throwOnError);
1759                         }
1760                         
1761                         InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
1762                         if (desc != null) return GenerateInstance (desc, throwOnError);
1763                         
1764                         if (throwOnError)
1765                                 throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
1766                         else
1767                                 return null;
1768                 }
1769                 
1770                 InstanceDescriptor GetDefaultInstanceDescriptor (object value)
1771                 {
1772                         if (value is System.Web.UI.WebControls.Unit) {
1773                                 System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
1774                                 ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
1775                                         BindingFlags.Instance | BindingFlags.Public,
1776                                         null,
1777                                         new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
1778                                         null);
1779                                 
1780                                 return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
1781                         }
1782                         
1783                         if (value is System.Web.UI.WebControls.FontUnit) {
1784                                 System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
1785
1786                                 Type cParamType = null;
1787                                 object cParam = null;
1788
1789                                 switch (s.Type) {
1790                                         case FontSize.AsUnit:
1791                                         case FontSize.NotSet:
1792                                                 cParamType = typeof (System.Web.UI.WebControls.Unit);
1793                                                 cParam = s.Unit;
1794                                                 break;
1795
1796                                         default:
1797                                                 cParamType = typeof (string);
1798                                                 cParam = s.Type.ToString ();
1799                                                 break;
1800                                 }
1801                                 
1802                                 ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
1803                                         BindingFlags.Instance | BindingFlags.Public,
1804                                         null,
1805                                         new Type[] {cParamType},
1806                                         null);
1807                                 if (c != null)
1808                                         return new InstanceDescriptor (c, new object[] {cParam});
1809                         }
1810                         return null;
1811                 }
1812         }
1813 }
1814
1815
1816