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