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