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