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