File: TemplateControlCompiler.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (2243 lines) | stat: -rw-r--r-- 81,108 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
//
// System.Web.Compilation.TemplateControlCompiler
//
// Authors:
//	Gonzalo Paniagua Javier (gonzalo@ximian.com)
//	Marek Habersack (mhabersack@novell.com)
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
// (C) 2004-2008 Novell, Inc (http://novell.com)

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.CodeDom;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
using System.ComponentModel.Design.Serialization;
using System.Text.RegularExpressions;

namespace System.Web.Compilation
{
	class TemplateControlCompiler : BaseCompiler
	{
		static BindingFlags noCaseFlags = BindingFlags.Public | BindingFlags.NonPublic |
						  BindingFlags.Instance | BindingFlags.IgnoreCase;
		static Type monoTypeType = Type.GetType ("System.MonoType");
		
		TemplateControlParser parser;
		int dataBoundAtts;
		internal ILocation currentLocation;

		static TypeConverter colorConverter;

		internal static CodeVariableReferenceExpression ctrlVar = new CodeVariableReferenceExpression ("__ctrl");
		
		List <string> masterPageContentPlaceHolders;
		static Regex startsWithBindRegex = new Regex (@"^Bind\s*\(", RegexOptions.Compiled | RegexOptions.IgnoreCase);
		// When modifying those, make sure to look at the SanitizeBindCall to make sure it
		// picks up correct groups.
		static Regex bindRegex = new Regex (@"Bind\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)\s*%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
		static Regex bindRegexInValue = new Regex (@"Bind\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
		static Regex evalRegexInValue = new Regex (@"(.*)Eval\s*\(\s*[""']+(.*?)[""']+((\s*,\s*[""']+(.*?)[""']+)?)\s*\)(.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

		List <string> MasterPageContentPlaceHolders {
			get {
				if (masterPageContentPlaceHolders == null)
					masterPageContentPlaceHolders = new List <string> ();
				return masterPageContentPlaceHolders;
			}
		}

		public TemplateControlCompiler (TemplateControlParser parser)
			: base (parser)
		{
			this.parser = parser;
		}

		protected void EnsureID (ControlBuilder builder)
		{
			string id = builder.ID;
			if (id == null || id.Trim () == String.Empty)
				builder.ID = builder.GetNextID (null);
		}

		void CreateField (ControlBuilder builder, bool check)
		{
			if (builder == null || builder.ID == null || builder.ControlType == null)
				return;

			if (partialNameOverride [builder.ID] != null)
				return;

			MemberAttributes ma = MemberAttributes.Family;
			currentLocation = builder.Location;
			if (check && CheckBaseFieldOrProperty (builder.ID, builder.ControlType, ref ma))
				return; // The field or property already exists in a base class and is accesible.

			CodeMemberField field;
			field = new CodeMemberField (builder.ControlType.FullName, builder.ID);
			field.Attributes = ma;
			field.Type.Options |= CodeTypeReferenceOptions.GlobalReference;

			if (partialClass != null)
				partialClass.Members.Add (AddLinePragma (field, builder));
			else
				mainClass.Members.Add (AddLinePragma (field, builder));
		}

		bool CheckBaseFieldOrProperty (string id, Type type, ref MemberAttributes ma)
		{
			FieldInfo fld = parser.BaseType.GetField (id, noCaseFlags);

			Type other = null;
			if (fld == null || fld.IsPrivate) {
				PropertyInfo prop = parser.BaseType.GetProperty (id, noCaseFlags);
				if (prop != null) {
					MethodInfo setm = prop.GetSetMethod (true);
					if (setm != null)
						other = prop.PropertyType;
				}
			} else {
				other = fld.FieldType;
			}
			
			if (other == null)
				return false;

			if (!other.IsAssignableFrom (type)) {
				ma |= MemberAttributes.New;
				return false;
			}

			return true;
		}
		
		void AddParsedSubObjectStmt (ControlBuilder builder, CodeExpression expr) 
		{
			if (!builder.HaveParserVariable) {
				CodeVariableDeclarationStatement p = new CodeVariableDeclarationStatement();
				p.Name = "__parser";
				p.Type = new CodeTypeReference (typeof (IParserAccessor));
				p.InitExpression = new CodeCastExpression (typeof (IParserAccessor), ctrlVar);
				builder.MethodStatements.Add (p);
				builder.HaveParserVariable = true;
			}

			CodeVariableReferenceExpression var = new CodeVariableReferenceExpression ("__parser");
			CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (var, "AddParsedSubObject");
			invoke.Parameters.Add (expr);
			builder.MethodStatements.Add (AddLinePragma (invoke, builder));
		}

		CodeStatement CreateControlVariable (Type type, ControlBuilder builder, CodeMemberMethod method, CodeTypeReference ctrlTypeRef)
		{
			CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression (ctrlTypeRef);

			object [] atts = type != null ? type.GetCustomAttributes (typeof (ConstructorNeedsTagAttribute), true) : null;
			if (atts != null && atts.Length > 0) {
				ConstructorNeedsTagAttribute att = (ConstructorNeedsTagAttribute) atts [0];
				if (att.NeedsTag)
					newExpr.Parameters.Add (new CodePrimitiveExpression (builder.TagName));
			} else if (builder is DataBindingBuilder) {
				newExpr.Parameters.Add (new CodePrimitiveExpression (0));
				newExpr.Parameters.Add (new CodePrimitiveExpression (1));
			}

			method.Statements.Add (new CodeVariableDeclarationStatement (ctrlTypeRef, "__ctrl"));
			CodeAssignStatement assign = new CodeAssignStatement ();
			assign.Left = ctrlVar;
			assign.Right = newExpr;

			return assign;
		}
		
		void InitMethod (ControlBuilder builder, bool isTemplate, bool childrenAsProperties)
		{
			currentLocation = builder.Location;
			bool inBuildControlTree = builder is RootBuilder;
			string tailname = (inBuildControlTree ? "Tree" : ("_" + builder.ID));
//			bool isProperty = builder.IsProperty;
			CodeMemberMethod method = new CodeMemberMethod ();
			builder.Method = method;
			builder.MethodStatements = method.Statements;

			method.Name = "__BuildControl" + tailname;
			method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			Type type = builder.ControlType;
			
			/* in the case this is the __BuildControlTree
			 * method, allow subclasses to insert control
			 * specific code. */
			if (inBuildControlTree) {
				SetCustomAttributes (method);
				AddStatementsToInitMethodTop (builder, method);
			}
			
			if (builder.HasAspCode) {
				CodeMemberMethod renderMethod = new CodeMemberMethod ();
				builder.RenderMethod = renderMethod;
				renderMethod.Name = "__Render" + tailname;
				renderMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
				CodeParameterDeclarationExpression arg1 = new CodeParameterDeclarationExpression ();
				arg1.Type = new CodeTypeReference (typeof (HtmlTextWriter));
				arg1.Name = "__output";
				CodeParameterDeclarationExpression arg2 = new CodeParameterDeclarationExpression ();
				arg2.Type = new CodeTypeReference (typeof (Control));
				arg2.Name = "parameterContainer";
				renderMethod.Parameters.Add (arg1);
				renderMethod.Parameters.Add (arg2);
				mainClass.Members.Add (renderMethod);
			}
			
			if (childrenAsProperties || type == null) {
				string typeString;
				bool isGlobal = true;
				bool returnsControl;

				if (builder is RootBuilder) {
					typeString = parser.ClassName;
					isGlobal = false;
					returnsControl = false;
				} else {
					returnsControl = builder.PropertyBuilderShouldReturnValue;
					if (type != null && builder.IsProperty && !typeof (ITemplate).IsAssignableFrom (type)) {
						typeString = type.FullName;
						isGlobal = !type.IsPrimitive;
					} else 
						typeString = "System.Web.UI.Control";
					ProcessTemplateChildren (builder);
				}
				CodeTypeReference ctrlTypeRef = new CodeTypeReference (typeString);
				if (isGlobal)
					ctrlTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
				
				if (returnsControl) {
					method.ReturnType = ctrlTypeRef;

					// $controlType _ctrl = new $controlType ($parameters);
					//
					method.Statements.Add (CreateControlVariable (type, builder, method, ctrlTypeRef));
				} else
					method.Parameters.Add (new CodeParameterDeclarationExpression (typeString, "__ctrl"));
			} else {
				CodeTypeReference ctrlTypeRef = new CodeTypeReference (type.FullName);
				if (!type.IsPrimitive)
					ctrlTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
				
				if (typeof (Control).IsAssignableFrom (type))
					method.ReturnType = ctrlTypeRef;

				// $controlType _ctrl = new $controlType ($parameters);
				//
				method.Statements.Add (AddLinePragma (CreateControlVariable (type, builder, method, ctrlTypeRef), builder));
								
				// this.$builderID = _ctrl;
				//
				CodeFieldReferenceExpression builderID = new CodeFieldReferenceExpression ();
				builderID.TargetObject = thisRef;
				builderID.FieldName = builder.ID;
				CodeAssignStatement assign = new CodeAssignStatement ();
				assign.Left = builderID;
				assign.Right = ctrlVar;
				method.Statements.Add (AddLinePragma (assign, builder));

				if (typeof (UserControl).IsAssignableFrom (type)) {
					CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression ();
					mref.TargetObject = builderID;
					mref.MethodName = "InitializeAsUserControl";
					CodeMethodInvokeExpression initAsControl = new CodeMethodInvokeExpression (mref);
					initAsControl.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
					method.Statements.Add (initAsControl);
				}

				if (builder.ParentTemplateBuilder is System.Web.UI.WebControls.ContentBuilderInternal) {
					PropertyInfo pi;

					try {
						pi = type.GetProperty ("TemplateControl");
					} catch (Exception) {
						pi = null;
					}

					if (pi != null && pi.CanWrite) {
						// __ctrl.TemplateControl = this;
						assign = new CodeAssignStatement ();
						assign.Left = new CodePropertyReferenceExpression (ctrlVar, "TemplateControl");;
						assign.Right = thisRef;
						method.Statements.Add (assign);
					}
				}
				
				// _ctrl.SkinID = $value
				// _ctrl.ApplyStyleSheetSkin (this);
				//
				// the SkinID assignment needs to come
				// before the call to
				// ApplyStyleSheetSkin, for obvious
				// reasons.  We skip SkinID in
				// CreateAssignStatementsFromAttributes
				// below.
				// 
				string skinid = builder.GetAttribute ("skinid");
				if (!String.IsNullOrEmpty (skinid))
					CreateAssignStatementFromAttribute (builder, "skinid");

				if (typeof (WebControl).IsAssignableFrom (type)) {
					CodeMethodInvokeExpression applyStyleSheetSkin = new CodeMethodInvokeExpression (ctrlVar, "ApplyStyleSheetSkin");
					if (typeof (Page).IsAssignableFrom (parser.BaseType))
						applyStyleSheetSkin.Parameters.Add (thisRef);
					else
						applyStyleSheetSkin.Parameters.Add (new CodePropertyReferenceExpression (thisRef, "Page"));
					method.Statements.Add (applyStyleSheetSkin);
				}

				// Process template children before anything else
				ProcessTemplateChildren (builder);

				// process ID here. It should be set before any other attributes are
				// assigned, since the control code may rely on ID being set. We
				// skip ID in CreateAssignStatementsFromAttributes
				string ctl_id = builder.GetAttribute ("id");
				if (ctl_id != null && ctl_id.Length != 0)
					CreateAssignStatementFromAttribute (builder, "id");
				
				if (typeof (ContentPlaceHolder).IsAssignableFrom (type)) {
					List <string> placeHolderIds = MasterPageContentPlaceHolders;
					string cphID = builder.ID;
					
					if (!placeHolderIds.Contains (cphID))
						placeHolderIds.Add (cphID);

					CodeConditionStatement condStatement;

					// Add the __Template_* field
					string templateField = "__Template_" + cphID;
					CodeMemberField fld = new CodeMemberField (typeof (ITemplate), templateField);
					fld.Attributes = MemberAttributes.Private;
					mainClass.Members.Add (fld);

					CodeFieldReferenceExpression templateID = new CodeFieldReferenceExpression ();
					templateID.TargetObject = thisRef;
					templateID.FieldName = templateField;

					CreateContentPlaceHolderTemplateProperty (templateField, "Template_" + cphID);
					
					// if ((this.ContentTemplates != null)) {
					// 	this.__Template_$builder.ID = ((System.Web.UI.ITemplate)(this.ContentTemplates["$builder.ID"]));
					// }
					//
					CodeFieldReferenceExpression contentTemplates = new CodeFieldReferenceExpression ();
					contentTemplates.TargetObject = thisRef;
					contentTemplates.FieldName = "ContentTemplates";

					CodeIndexerExpression indexer = new CodeIndexerExpression ();
					indexer.TargetObject = new CodePropertyReferenceExpression (thisRef, "ContentTemplates");
					indexer.Indices.Add (new CodePrimitiveExpression (cphID));

					assign = new CodeAssignStatement ();
					assign.Left = templateID;
					assign.Right = new CodeCastExpression (new CodeTypeReference (typeof (ITemplate)), indexer);

					condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (contentTemplates,
														      CodeBinaryOperatorType.IdentityInequality,
														      new CodePrimitiveExpression (null)),
										    assign);

					method.Statements.Add (condStatement);

					// if ((this.__Template_mainContent != null)) {
					// 	this.__Template_mainContent.InstantiateIn(__ctrl);
					// }
					// and also set things up such that any additional code ends up in:
					// else {
					// 	...
					// }
					//
					CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
					methodRef.TargetObject = templateID;
					methodRef.MethodName = "InstantiateIn";

					CodeMethodInvokeExpression instantiateInInvoke;
					instantiateInInvoke = new CodeMethodInvokeExpression (methodRef, ctrlVar);

					condStatement = new CodeConditionStatement (new CodeBinaryOperatorExpression (templateID,
														      CodeBinaryOperatorType.IdentityInequality,
														      new CodePrimitiveExpression (null)),
										    new CodeExpressionStatement (instantiateInInvoke));
					method.Statements.Add (condStatement);

					// this is the bit that causes the following stuff to end up in the else { }
					builder.MethodStatements = condStatement.FalseStatements;
				}
			}

			if (inBuildControlTree)
				AddStatementsToInitMethodBottom (builder, method);
			
			mainClass.Members.Add (method);
		}

		void ProcessTemplateChildren (ControlBuilder builder)
		{
			ArrayList templates = builder.TemplateChildren;
			if (templates != null && templates.Count > 0) {
				foreach (TemplateBuilder tb in templates) {
					CreateControlTree (tb, true, false);
					if (tb.BindingDirection == BindingDirection.TwoWay) {
						string extractMethod = CreateExtractValuesMethod (tb);
						AddBindableTemplateInvocation (builder, tb.TagName, tb.Method.Name, extractMethod);
					} else
						AddTemplateInvocation (builder, tb.TagName, tb.Method.Name);
				}
			}
		}
		
		void SetCustomAttribute (CodeMemberMethod method, UnknownAttributeDescriptor uad)
		{
			CodeAssignStatement assign = new CodeAssignStatement ();
			assign.Left = new CodePropertyReferenceExpression (
				new CodeArgumentReferenceExpression("__ctrl"),
				uad.Info.Name);
			assign.Right = GetExpressionFromString (uad.Value.GetType (), uad.Value.ToString (), uad.Info);
			
			method.Statements.Add (assign);
		}
		
		void SetCustomAttributes (CodeMemberMethod method)
		{
			Type baseType = parser.BaseType;
			if (baseType == null)
				return;
			
			List <UnknownAttributeDescriptor> attrs = parser.UnknownMainAttributes;
			if (attrs == null || attrs.Count == 0)
				return;

			foreach (UnknownAttributeDescriptor uad in attrs)
				SetCustomAttribute (method, uad);
		}
		
		protected virtual void AddStatementsToInitMethodTop (ControlBuilder builder, CodeMemberMethod method)
		{
#if NET_4_0
			ClientIDMode? mode = parser.ClientIDMode;
			if (mode.HasValue) {
				var cimRef = new CodeTypeReferenceExpression (typeof (ClientIDMode));
				cimRef.Type.Options = CodeTypeReferenceOptions.GlobalReference;
				
				var assign = new CodeAssignStatement ();
				assign.Left = new CodePropertyReferenceExpression (thisRef, "ClientIDMode");
				assign.Right = new CodeFieldReferenceExpression (cimRef, mode.Value.ToString ());

				method.Statements.Add (assign);
			}
#endif
		}

		protected virtual void AddStatementsToInitMethodBottom (ControlBuilder builder, CodeMemberMethod method)
		{
		}
		
		void AddLiteralSubObject (ControlBuilder builder, string str)
		{
			if (!builder.HasAspCode) {
				CodeObjectCreateExpression expr;
				expr = new CodeObjectCreateExpression (typeof (LiteralControl), new CodePrimitiveExpression (str));
				AddParsedSubObjectStmt (builder, expr);
			} else {
				CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression ();
				methodRef.TargetObject = new CodeArgumentReferenceExpression ("__output");
				methodRef.MethodName = "Write";

				CodeMethodInvokeExpression expr;
				expr = new CodeMethodInvokeExpression (methodRef, new CodePrimitiveExpression (str));
				builder.RenderMethod.Statements.Add (expr);
			}
		}

		string TrimDB (string value, bool trimTail)
		{
			string str = value.Trim ();
			int len = str.Length;
			int idx = str.IndexOf ('#', 2) + 1;
			if (idx >= len)
				return String.Empty;
			if (trimTail)
				len -= 2;
			
			return str.Substring (idx, len - idx).Trim ();
		}

		CodeExpression CreateEvalInvokeExpression (Regex regex, string value, bool isBind)
		{
			Match match = regex.Match (value);
			if (!match.Success) {
				if (isBind)
					throw new HttpParseException ("Bind invocation wasn't formatted properly.");
				return null;
			}
			
			string sanitizedSnippet;
			if (isBind)
				sanitizedSnippet = SanitizeBindCall (match);
			else
				sanitizedSnippet = value;
			
			return new CodeSnippetExpression (sanitizedSnippet);
		}

		string SanitizeBindCall (Match match)
		{
			GroupCollection groups = match.Groups;
			StringBuilder sb = new StringBuilder ("Eval(\"" + groups [1] + "\"");
			Group second = groups [4];
			if (second != null) {
				string v = second.Value;
				if (v != null && v.Length > 0)
					sb.Append (",\"" + second + "\"");
			}
			
			sb.Append (")");
			return sb.ToString ();
		}
		
		string DataBoundProperty (ControlBuilder builder, Type type, string varName, string value)
		{
			value = TrimDB (value, true);
			CodeMemberMethod method;
			string dbMethodName = builder.Method.Name + "_DB_" + dataBoundAtts++;
			CodeExpression valueExpression = null;
			value = value.Trim ();
			
			bool need_if = false;
			if (startsWithBindRegex.Match (value).Success) {
				valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, true);
				if (valueExpression != null)
					need_if = true;
			} else
				if (StrUtils.StartsWith (value, "Eval", true))
					valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, false);
			
			if (valueExpression == null)
				valueExpression = new CodeSnippetExpression (value);
			
			method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
			CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");

			// This should be a CodePropertyReferenceExpression for properties... but it works anyway
			CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (targetExpr, varName);

			CodeExpression expr;
			if (type == typeof (string)) {
				CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
				CodeTypeReferenceExpression conv = new CodeTypeReferenceExpression (typeof (Convert));
				tostring.Method = new CodeMethodReferenceExpression (conv, "ToString");
				tostring.Parameters.Add (valueExpression);
				expr = tostring;
			} else
				expr = new CodeCastExpression (type, valueExpression);

			CodeAssignStatement assign = new CodeAssignStatement (field, expr);
			if (need_if) {
				CodeExpression page = new CodePropertyReferenceExpression (thisRef, "Page");
				CodeExpression left = new CodeMethodInvokeExpression (page, "GetDataItem");
				CodeBinaryOperatorExpression ce = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
				CodeConditionStatement ccs = new CodeConditionStatement (ce, assign);
				method.Statements.Add (ccs);
			} else
				method.Statements.Add (assign);

			mainClass.Members.Add (method);
			return method.Name;
		}

		void AddCodeForPropertyOrField (ControlBuilder builder, Type type, string var_name, string att, MemberInfo member, bool isDataBound, bool isExpression)
		{
			CodeMemberMethod method = builder.Method;
			bool isWritable = IsWritablePropertyOrField (member);
			
			if (isDataBound && isWritable) {
				string dbMethodName = DataBoundProperty (builder, type, var_name, att);
				AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
				return;
			} else if (isExpression && isWritable) {
				AddExpressionAssign (method, builder, member, type, var_name, att);
				return;
			}

			CodeAssignStatement assign = new CodeAssignStatement ();
			assign.Left = new CodePropertyReferenceExpression (ctrlVar, var_name);
			currentLocation = builder.Location;
			assign.Right = GetExpressionFromString (type, att, member);

			method.Statements.Add (AddLinePragma (assign, builder));
		}

		void RegisterBindingInfo (ControlBuilder builder, string propName, ref string value)
		{
			string str = TrimDB (value, false);
			if (StrUtils.StartsWith (str, "Bind", true)) {
				Match match = bindRegex.Match (str);
				if (match.Success) {
					string bindingName = match.Groups [1].Value;
					TemplateBuilder templateBuilder = builder.ParentTemplateBuilder;
					
					if (templateBuilder == null)
						throw new HttpException ("Bind expression not allowed in this context.");

					if (templateBuilder.BindingDirection == BindingDirection.OneWay)
						return;
					
					string id = builder.GetAttribute ("ID");
					if (String.IsNullOrEmpty (id))
						throw new HttpException ("Control of type '" + builder.ControlType + "' using two-way binding on property '" + propName + "' must have an ID.");
					
					templateBuilder.RegisterBoundProperty (builder.ControlType, propName, id, bindingName);
				}
			}
		}

		/*
		static bool InvariantCompare (string a, string b)
		{
			return (0 == String.Compare (a, b, false, Helpers.InvariantCulture));
		}
		*/

		static bool InvariantCompareNoCase (string a, string b)
		{
			return (0 == String.Compare (a, b, true, Helpers.InvariantCulture));
		}

		internal static MemberInfo GetFieldOrProperty (Type type, string name)
		{
			MemberInfo member = null;
			try {
				member = type.GetProperty (name, noCaseFlags & ~BindingFlags.NonPublic);
			} catch {}
			
			if (member != null)
				return member;

			try {
				member = type.GetField (name, noCaseFlags & ~BindingFlags.NonPublic);
			} catch {}

			return member;
		}

		static bool IsWritablePropertyOrField (MemberInfo member)
		{
			PropertyInfo pi = member as PropertyInfo;
			if (pi != null)
				return pi.GetSetMethod (false) != null;
			FieldInfo fi = member as FieldInfo;
			if (fi != null)
				return !fi.IsInitOnly;
			throw new ArgumentException ("Argument must be of PropertyInfo or FieldInfo type", "member");
		}

		bool ProcessPropertiesAndFields (ControlBuilder builder, MemberInfo member, string id,
						 string attValue, string prefix)
		{
			int hyphen = id.IndexOf ('-');
			bool isPropertyInfo = (member is PropertyInfo);
			bool isDataBound = BaseParser.IsDataBound (attValue);
			bool isExpression = !isDataBound && BaseParser.IsExpression (attValue);
			Type type;
			if (isPropertyInfo) {
				type = ((PropertyInfo) member).PropertyType;
			} else {
				type = ((FieldInfo) member).FieldType;
			}

			if (InvariantCompareNoCase (member.Name, id)) {
				if (isDataBound)
					RegisterBindingInfo (builder, member.Name, ref attValue);				

				if (!IsWritablePropertyOrField (member))
					return false;
				
				AddCodeForPropertyOrField (builder, type, member.Name, attValue, member, isDataBound, isExpression);
				return true;
			}
			
			if (hyphen == -1)
				return false;

			string prop_field = id.Replace ('-', '.');
			string [] parts = prop_field.Split (new char [] {'.'});
			int length = parts.Length;
			
			if (length < 2 || !InvariantCompareNoCase (member.Name, parts [0]))
				return false;

			if (length > 2) {
				MemberInfo sub_member = GetFieldOrProperty (type, parts [1]);
				if (sub_member == null)
					return false;

				string new_prefix = prefix + member.Name + ".";
				string new_id = id.Substring (hyphen + 1);
				return ProcessPropertiesAndFields (builder, sub_member, new_id, attValue, new_prefix);
			}

			MemberInfo subpf = GetFieldOrProperty (type, parts [1]);
			if (!(subpf is PropertyInfo))
				return false;

			PropertyInfo subprop = (PropertyInfo) subpf;
			if (subprop.CanWrite == false)
				return false;

			bool is_bool = (subprop.PropertyType == typeof (bool));
			if (!is_bool && attValue == null)
				return false; // Font-Size -> Font-Size="" as html

			string val = attValue;
			if (attValue == null && is_bool)
				val = "true"; // Font-Bold <=> Font-Bold="true"

			if (isDataBound)
				RegisterBindingInfo (builder, prefix + member.Name + "." + subprop.Name, ref attValue);

			AddCodeForPropertyOrField (builder, subprop.PropertyType,
						   prefix + member.Name + "." + subprop.Name,
						   val, subprop, isDataBound, isExpression);

			return true;
		}

		internal CodeExpression CompileExpression (MemberInfo member, Type type, string value, bool useSetAttribute)
		{
			// First let's find the correct expression builder
			value = value.Substring (3, value.Length - 5).Trim ();
			int colon = value.IndexOf (':');
			if (colon == -1)
				return null;
			string prefix = value.Substring (0, colon).Trim ();
			string expr = value.Substring (colon + 1).Trim ();
			
			CompilationSection cs = (CompilationSection)WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
			if (cs == null)
				return null;
			
			if (cs.ExpressionBuilders == null || cs.ExpressionBuilders.Count == 0)
				return null;

			System.Web.Configuration.ExpressionBuilder ceb = cs.ExpressionBuilders[prefix];
			if (ceb == null)
				return null;
			
			string builderType = ceb.Type;
			Type t;
			
			try {
				t = HttpApplication.LoadType (builderType, true);
			} catch (Exception e) {
				throw new HttpException (String.Format ("Failed to load expression builder type `{0}'", builderType), e);
			}

			if (!typeof (System.Web.Compilation.ExpressionBuilder).IsAssignableFrom (t))
				throw new HttpException (String.Format ("Type {0} is not descendant from System.Web.Compilation.ExpressionBuilder", builderType));

			System.Web.Compilation.ExpressionBuilder eb = null;
			object parsedData;
			ExpressionBuilderContext ctx;
			
			try {
				eb = Activator.CreateInstance (t) as System.Web.Compilation.ExpressionBuilder;
				ctx = new ExpressionBuilderContext (HttpContext.Current.Request.FilePath);
				parsedData = eb.ParseExpression (expr, type, ctx);
			} catch (Exception e) {
				throw new HttpException (String.Format ("Failed to create an instance of type `{0}'", builderType), e);
			}
			
			BoundPropertyEntry bpe = CreateBoundPropertyEntry (member as PropertyInfo, prefix, expr, useSetAttribute);
			return eb.GetCodeExpression (bpe, parsedData, ctx);
		}
		
		void AddExpressionAssign (CodeMemberMethod method, ControlBuilder builder, MemberInfo member, Type type, string name, string value)
		{
			CodeExpression expr = CompileExpression (member, type, value, false);

			if (expr == null)
				return;
			
			CodeAssignStatement assign = new CodeAssignStatement ();
			assign.Left = new CodePropertyReferenceExpression (ctrlVar, name);

			TypeCode typeCode = Type.GetTypeCode (type);
			if (typeCode != TypeCode.Empty && typeCode != TypeCode.Object && typeCode != TypeCode.DBNull)
				assign.Right = CreateConvertToCall (typeCode, expr);
			else 
				assign.Right = new CodeCastExpression (type, expr);
			
			builder.Method.Statements.Add (AddLinePragma (assign, builder));
		}

		internal static CodeMethodInvokeExpression CreateConvertToCall (TypeCode typeCode, CodeExpression expr)
		{
			var ret = new CodeMethodInvokeExpression ();
			string methodName;

			switch (typeCode) {
				case TypeCode.Boolean:
					methodName = "ToBoolean";
					break;

				case TypeCode.Char:
					methodName = "ToChar";
					break;

				case TypeCode.SByte:
					methodName = "ToSByte";
					break;

				case TypeCode.Byte:
					methodName = "ToByte";
					break;
					
				case TypeCode.Int16:
					methodName = "ToInt16";
					break;

				case TypeCode.UInt16:
					methodName = "ToUInt16";
					break;

				case TypeCode.Int32:
					methodName = "ToInt32";
					break;

				case TypeCode.UInt32:
					methodName = "ToUInt32";
					break;

				case TypeCode.Int64:
					methodName = "ToInt64";
					break;
					
				case TypeCode.UInt64:
					methodName = "ToUInt64";
					break;

				case TypeCode.Single:
					methodName = "ToSingle";
					break;

				case TypeCode.Double:
					methodName = "ToDouble";
					break;

				case TypeCode.Decimal:
					methodName = "ToDecimal";
					break;

				case TypeCode.DateTime:
					methodName = "ToDateTime";
					break;

				case TypeCode.String:
					methodName = "ToString";
					break;

				default:
					throw new InvalidOperationException (String.Format ("Unsupported TypeCode '{0}'", typeCode));
			}

			var typeRef = new CodeTypeReferenceExpression (typeof (Convert));
			typeRef.Type.Options = CodeTypeReferenceOptions.GlobalReference;
			
			ret.Method = new CodeMethodReferenceExpression (typeRef, methodName);
			ret.Parameters.Add (expr);
			ret.Parameters.Add (new CodePropertyReferenceExpression (new CodeTypeReferenceExpression (typeof (System.Globalization.CultureInfo)), "CurrentCulture"));
			
			return ret;
		}
		
		BoundPropertyEntry CreateBoundPropertyEntry (PropertyInfo pi, string prefix, string expr, bool useSetAttribute)
		{
			BoundPropertyEntry ret = new BoundPropertyEntry ();
			ret.Expression = expr;
			ret.ExpressionPrefix = prefix;
			ret.Generated = false;
			if (pi != null) {
				ret.Name = pi.Name;
				ret.PropertyInfo = pi;
				ret.Type = pi.PropertyType;
			}
			ret.UseSetAttribute = useSetAttribute;
			
			return ret;
		}

		bool ResourceProviderHasObject (string key)
		{
			IResourceProvider rp = HttpContext.GetResourceProvider (InputVirtualPath.Absolute, true);
			if (rp == null)
				return false;

			IResourceReader rr = rp.ResourceReader;
			if (rr == null)
				return false;

			try {
				IDictionaryEnumerator ide = rr.GetEnumerator ();
				if (ide == null)
					return false;
			
				string dictKey;
				while (ide.MoveNext ()) {
					dictKey = ide.Key as string;
					if (String.IsNullOrEmpty (dictKey))
						continue;
					if (String.Compare (key, dictKey, StringComparison.Ordinal) == 0)
						return true;
				}
			} finally {
				rr.Close ();
			}
			
			return false;
		}
		
		void AssignPropertyFromResources (ControlBuilder builder, MemberInfo mi, string attvalue)
		{
			bool isProperty = mi.MemberType == MemberTypes.Property;
			bool isField = !isProperty && (mi.MemberType == MemberTypes.Field);

			if (!isProperty && !isField || !IsWritablePropertyOrField (mi))
				return;			

			object[] attrs = mi.GetCustomAttributes (typeof (LocalizableAttribute), true);
			if (attrs != null && attrs.Length > 0 && !((LocalizableAttribute)attrs [0]).IsLocalizable)
				return;
			
			string memberName = mi.Name;
			string resname = String.Concat (attvalue, ".", memberName);

			if (!ResourceProviderHasObject (resname))
				return;
			
			// __ctrl.Text = System.Convert.ToString(HttpContext.GetLocalResourceObject("ButtonResource1.Text"));
			string inputFile = parser.InputFile;
			string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
	
			if (StrUtils.StartsWith (inputFile, physPath)) {
				string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
				inputFile = parser.InputFile.Substring (physPath.Length - 1);
				if (appVirtualPath != "/")
					inputFile = appVirtualPath + inputFile;
			} else
				return;

			char dsc = System.IO.Path.DirectorySeparatorChar;
			if (dsc != '/')
				inputFile = inputFile.Replace (dsc, '/');

			object obj = HttpContext.GetLocalResourceObject (inputFile, resname);
			if (obj == null)
				return;

			if (!isProperty && !isField)
				return; // an "impossible" case
			
			CodeAssignStatement assign = new CodeAssignStatement ();
			
			assign.Left = new CodePropertyReferenceExpression (ctrlVar, memberName);
			assign.Right = ResourceExpressionBuilder.CreateGetLocalResourceObject (mi, resname);
			
			builder.Method.Statements.Add (AddLinePragma (assign, builder));
		}

		void AssignPropertiesFromResources (ControlBuilder builder, Type controlType, string attvalue)
		{
			// Process all public fields and properties of the control. We don't use GetMembers to make the code
			// faster
			FieldInfo [] fields = controlType.GetFields (
				BindingFlags.Instance | BindingFlags.Static |
				BindingFlags.Public | BindingFlags.FlattenHierarchy);
			PropertyInfo [] properties = controlType.GetProperties (
				BindingFlags.Instance | BindingFlags.Static |
				BindingFlags.Public | BindingFlags.FlattenHierarchy);

			foreach (FieldInfo fi in fields)
				AssignPropertyFromResources (builder, fi, attvalue);
			foreach (PropertyInfo pi in properties)
				AssignPropertyFromResources (builder, pi, attvalue);
		}
		
		void AssignPropertiesFromResources (ControlBuilder builder, string attvalue)
		{
			if (attvalue == null || attvalue.Length == 0)
				return;
			
			Type controlType = builder.ControlType;
			if (controlType == null)
				return;

			AssignPropertiesFromResources (builder, controlType, attvalue);
		}
		
		void AddEventAssign (CodeMemberMethod method, ControlBuilder builder, string name, Type type, string value)
		{
			//"__ctrl.{0} += new {1} (this.{2});"
			CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);

			CodeDelegateCreateExpression create;
			create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);

			CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
			method.Statements.Add (attach);
		}
		
		void CreateAssignStatementFromAttribute (ControlBuilder builder, string id)
		{
			EventInfo [] ev_info = null;
			Type type = builder.ControlType;
			
			string attvalue = builder.GetAttribute (id);
			if (id.Length > 2 && String.Compare (id.Substring (0, 2), "ON", true, Helpers.InvariantCulture) == 0){
				if (ev_info == null)
					ev_info = type.GetEvents ();

				string id_as_event = id.Substring (2);
				foreach (EventInfo ev in ev_info){
					if (InvariantCompareNoCase (ev.Name, id_as_event)){
						AddEventAssign (builder.Method,
								builder,
								ev.Name,
								ev.EventHandlerType,
								attvalue);
						
						return;
					}
				}

			}

			if (String.Compare (id, "meta:resourcekey", StringComparison.OrdinalIgnoreCase) == 0) {
				AssignPropertiesFromResources (builder, attvalue);
				return;
			}
			
			int hyphen = id.IndexOf ('-');
			string alt_id = id;
			if (hyphen != -1)
				alt_id = id.Substring (0, hyphen);

			MemberInfo fop = GetFieldOrProperty (type, alt_id);
			if (fop != null) {
				if (ProcessPropertiesAndFields (builder, fop, id, attvalue, null))
					return;
			}

			if (!typeof (IAttributeAccessor).IsAssignableFrom (type))
				throw new ParseException (builder.Location, "Unrecognized attribute: " + id);

			CodeMemberMethod method = builder.Method;
			bool isDatabound = BaseParser.IsDataBound (attvalue);
			bool isExpression = !isDatabound && BaseParser.IsExpression (attvalue);

			if (isDatabound) {
				string value = attvalue.Substring (3, attvalue.Length - 5).Trim ();
				CodeExpression valueExpression = null;
				if (startsWithBindRegex.Match (value).Success)
					valueExpression = CreateEvalInvokeExpression (bindRegexInValue, value, true);
				else
					if (StrUtils.StartsWith (value, "Eval", true))
						valueExpression = CreateEvalInvokeExpression (evalRegexInValue, value, false);
				
				if (valueExpression == null && value != null && value.Trim () != String.Empty)
					valueExpression = new CodeSnippetExpression (value);
				
				CreateDBAttributeMethod (builder, id, valueExpression);
			} else {
				CodeCastExpression cast;
				CodeMethodReferenceExpression methodExpr;
				CodeMethodInvokeExpression expr;

				cast = new CodeCastExpression (typeof (IAttributeAccessor), ctrlVar);
				methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
				expr = new CodeMethodInvokeExpression (methodExpr);
				expr.Parameters.Add (new CodePrimitiveExpression (id));

				CodeExpression valueExpr = null;
				if (isExpression)
					valueExpr = CompileExpression (null, typeof (string), attvalue, true);

				if (valueExpr == null)
					valueExpr = new CodePrimitiveExpression (attvalue);
				
				expr.Parameters.Add (valueExpr);
				method.Statements.Add (AddLinePragma (expr, builder));
			}
		}

		protected void CreateAssignStatementsFromAttributes (ControlBuilder builder)
		{
			this.dataBoundAtts = 0;
			IDictionary atts = builder.Attributes;
			if (atts == null || atts.Count == 0)
				return;
			
			foreach (string id in atts.Keys) {
				if (InvariantCompareNoCase (id, "runat"))
					continue;
				// ID is assigned in BuildControltree
				if (InvariantCompareNoCase (id, "id"))
					continue;				

				/* we skip SkinID here as it's assigned in BuildControlTree */
				if (InvariantCompareNoCase (id, "skinid"))
					continue;
				if (InvariantCompareNoCase (id, "meta:resourcekey"))
					continue; // ignore, this one's processed at the very end of
						  // the method
				CreateAssignStatementFromAttribute (builder, id);
			}
		}

		void CreateDBAttributeMethod (ControlBuilder builder, string attr, CodeExpression code)
		{
			if (code == null)
				return;

			string id = builder.GetNextID (null);
			string dbMethodName = "__DataBind_" + id;
			CodeMemberMethod method = builder.Method;
			AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);

			method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), builder.ControlType);
			builder.DataBindingMethod = method;

			CodeCastExpression cast;
			CodeMethodReferenceExpression methodExpr;
			CodeMethodInvokeExpression expr;

			CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
			cast = new CodeCastExpression (typeof (IAttributeAccessor), targetExpr);
			methodExpr = new CodeMethodReferenceExpression (cast, "SetAttribute");
			expr = new CodeMethodInvokeExpression (methodExpr);
			expr.Parameters.Add (new CodePrimitiveExpression (attr));
			CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
			tostring.Method = new CodeMethodReferenceExpression (
							new CodeTypeReferenceExpression (typeof (Convert)),
							"ToString");
			tostring.Parameters.Add (code);
			expr.Parameters.Add (tostring);
			method.Statements.Add (expr);
			mainClass.Members.Add (method);
		}

		void AddRenderControl (ControlBuilder builder)
		{
			CodeIndexerExpression indexer = new CodeIndexerExpression ();
			indexer.TargetObject = new CodePropertyReferenceExpression (
							new CodeArgumentReferenceExpression ("parameterContainer"),
							"Controls");
							
			indexer.Indices.Add (new CodePrimitiveExpression (builder.RenderIndex));
			
			CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (indexer, "RenderControl");
			invoke.Parameters.Add (new CodeArgumentReferenceExpression ("__output"));
			builder.RenderMethod.Statements.Add (invoke);
			builder.IncreaseRenderIndex ();
		}

		protected void AddChildCall (ControlBuilder parent, ControlBuilder child)
		{
			if (parent == null || child == null)
				return;

			CodeStatementCollection methodStatements = parent.MethodStatements;
			CodeMethodReferenceExpression m = new CodeMethodReferenceExpression (thisRef, child.Method.Name);
			CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (m);

			object [] atts = null;

			if (child.ControlType != null)
				atts = child.ControlType.GetCustomAttributes (typeof (PartialCachingAttribute), true);
			
			if (atts != null && atts.Length > 0) {
				PartialCachingAttribute pca = (PartialCachingAttribute) atts [0];
				CodeTypeReferenceExpression cc = new CodeTypeReferenceExpression("System.Web.UI.StaticPartialCachingControl");
				CodeMethodInvokeExpression build = new CodeMethodInvokeExpression (cc, "BuildCachedControl");
				CodeExpressionCollection parms = build.Parameters;
				
				parms.Add (new CodeArgumentReferenceExpression("__ctrl"));
				parms.Add (new CodePrimitiveExpression (child.ID));

				if (pca.Shared)
					parms.Add (new CodePrimitiveExpression (child.ControlType.GetHashCode ().ToString ()));
				else
					parms.Add (new CodePrimitiveExpression (Guid.NewGuid ().ToString ()));
					
				parms.Add (new CodePrimitiveExpression (pca.Duration));
				parms.Add (new CodePrimitiveExpression (pca.VaryByParams));
				parms.Add (new CodePrimitiveExpression (pca.VaryByControls));
				parms.Add (new CodePrimitiveExpression (pca.VaryByCustom));
				parms.Add (new CodePrimitiveExpression (pca.SqlDependency));
				parms.Add (new CodeDelegateCreateExpression (
							      new CodeTypeReference (typeof (System.Web.UI.BuildMethod)),
							      thisRef, child.Method.Name));
#if NET_4_0
				string value = pca.ProviderName;
				if (!String.IsNullOrEmpty (value) && String.Compare (OutputCache.DEFAULT_PROVIDER_NAME, value, StringComparison.Ordinal) != 0)
					parms.Add (new CodePrimitiveExpression (value));
				else
					parms.Add (new CodePrimitiveExpression (null));
#endif
				methodStatements.Add (AddLinePragma (build, parent));
				if (parent.HasAspCode)
					AddRenderControl (parent);
				return;
			}
                                
			if (child.IsProperty || parent.ChildrenAsProperties) {
				if (!child.PropertyBuilderShouldReturnValue) {
					expr.Parameters.Add (new CodeFieldReferenceExpression (ctrlVar, child.TagName));
					parent.MethodStatements.Add (AddLinePragma (expr, parent));
				} else {
					string localVarName = parent.GetNextLocalVariableName ("__ctrl");
					methodStatements.Add (new CodeVariableDeclarationStatement (child.Method.ReturnType, localVarName));
					CodeVariableReferenceExpression localVarRef = new CodeVariableReferenceExpression (localVarName);
					CodeAssignStatement assign = new CodeAssignStatement ();
					assign.Left = localVarRef;
					assign.Right = expr;
					methodStatements.Add (AddLinePragma (assign, parent));

					assign = new CodeAssignStatement ();
					assign.Left = new CodeFieldReferenceExpression (ctrlVar, child.TagName);
					assign.Right = localVarRef;
					methodStatements.Add (AddLinePragma (assign, parent));
				}
				
				return;
			}

			methodStatements.Add (AddLinePragma (expr, parent));
			CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, child.ID);
			if (parent.ControlType == null || typeof (IParserAccessor).IsAssignableFrom (parent.ControlType))
				AddParsedSubObjectStmt (parent, field);
			else {
				CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (ctrlVar, "Add");
				invoke.Parameters.Add (field);
				methodStatements.Add (AddLinePragma (invoke, parent));
			}
				
			if (parent.HasAspCode)
				AddRenderControl (parent);
		}

		void AddTemplateInvocation (ControlBuilder builder, string name, string methodName)
		{
			CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);

			CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
				new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);

			CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
			newCompiled.Parameters.Add (newBuild);

			CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
			builder.Method.Statements.Add (AddLinePragma (assign, builder));
		}

		void AddBindableTemplateInvocation (ControlBuilder builder, string name, string methodName, string extractMethodName)
		{
			CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);

			CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
				new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);

			CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
				new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);

			CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
			newCompiled.Parameters.Add (newBuild);
			newCompiled.Parameters.Add (newExtract);
			
			CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
			builder.Method.Statements.Add (AddLinePragma (assign, builder));
		}
		
		string CreateExtractValuesMethod (TemplateBuilder builder)
		{
			CodeMemberMethod method = new CodeMemberMethod ();
			method.Name = "__ExtractValues_" + builder.ID;
			method.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			method.ReturnType = new CodeTypeReference (typeof(IOrderedDictionary));
			
			CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression ();
			arg.Type = new CodeTypeReference (typeof (Control));
			arg.Name = "__container";
			method.Parameters.Add (arg);
			mainClass.Members.Add (method);
			
			CodeObjectCreateExpression newTable = new CodeObjectCreateExpression ();
			newTable.CreateType = new CodeTypeReference (typeof(OrderedDictionary));
			method.Statements.Add (new CodeVariableDeclarationStatement (typeof(OrderedDictionary), "__table", newTable));
			CodeVariableReferenceExpression tableExp = new CodeVariableReferenceExpression ("__table");
			
			if (builder.Bindings != null) {
				Hashtable hash = new Hashtable ();
				foreach (TemplateBinding binding in builder.Bindings) {
					CodeConditionStatement sif;
					CodeVariableReferenceExpression control;
					CodeAssignStatement assign;

					if (hash [binding.ControlId] == null) {

						CodeVariableDeclarationStatement dec = new CodeVariableDeclarationStatement (binding.ControlType, binding.ControlId);
						method.Statements.Add (dec);
						CodeVariableReferenceExpression cter = new CodeVariableReferenceExpression ("__container");
						CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (cter, "FindControl");
						invoke.Parameters.Add (new CodePrimitiveExpression (binding.ControlId));

						assign = new CodeAssignStatement ();
						control = new CodeVariableReferenceExpression (binding.ControlId);
						assign.Left = control;
						assign.Right = new CodeCastExpression (binding.ControlType, invoke);
						method.Statements.Add (assign);

						sif = new CodeConditionStatement ();
						sif.Condition = new CodeBinaryOperatorExpression (control, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));

						method.Statements.Add (sif);

						hash [binding.ControlId] = sif;
					}

					sif = (CodeConditionStatement) hash [binding.ControlId];
					control = new CodeVariableReferenceExpression (binding.ControlId);
					assign = new CodeAssignStatement ();
					assign.Left = new CodeIndexerExpression (tableExp, new CodePrimitiveExpression (binding.FieldName));
					assign.Right = new CodePropertyReferenceExpression (control, binding.ControlProperty);
					sif.TrueStatements.Add (assign);
				}
			}

			method.Statements.Add (new CodeMethodReturnStatement (tableExp));
			return method.Name;
		}

		void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
		{
			CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
				new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);

			CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
			newCompiled.Parameters.Add (newBuild);
			
			CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
			invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
			invoke.Parameters.Add (newCompiled);

			method.Statements.Add (AddLinePragma (invoke, cbuilder));
		}

		void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
		{
			if (cr.Code == null || cr.Code.Trim () == "")
				return;

			if (!cr.IsAssign) {
				CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
				parent.RenderMethod.Statements.Add (AddLinePragma (code, cr));
				return;
			}

			CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
			expr.Method = new CodeMethodReferenceExpression (
							new CodeArgumentReferenceExpression ("__output"),
							"Write");

			expr.Parameters.Add (GetWrappedCodeExpression (cr));
			parent.RenderMethod.Statements.Add (AddLinePragma (expr, cr));
		}

		CodeExpression GetWrappedCodeExpression (CodeRenderBuilder cr)
		{
			var ret = new CodeSnippetExpression (cr.Code);
#if NET_4_0
			if (cr.HtmlEncode) {
				var encodeRef = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (HttpUtility)), "HtmlEncode");
				return new CodeMethodInvokeExpression (encodeRef, new CodeExpression[] { ret });
			} else
#endif
				return ret;
		}
		
		static Type GetContainerType (ControlBuilder builder)
		{
			return builder.BindingContainerType;
		}
		
		CodeMemberMethod CreateDBMethod (ControlBuilder builder, string name, Type container, Type target)
		{
			CodeMemberMethod method = new CodeMemberMethod ();
			method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			method.Name = name;
			method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
			method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));

			CodeTypeReference containerRef = new CodeTypeReference (container);
			CodeTypeReference targetRef = new CodeTypeReference (target);

			CodeVariableDeclarationStatement decl = new CodeVariableDeclarationStatement();
			decl.Name = "Container";
			decl.Type = containerRef;
			method.Statements.Add (decl);
			
			decl = new CodeVariableDeclarationStatement();
			decl.Name = "target";
			decl.Type = targetRef;
			method.Statements.Add (decl);

			CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
			CodeAssignStatement assign = new CodeAssignStatement ();
			assign.Left = targetExpr;
			assign.Right = new CodeCastExpression (targetRef, new CodeArgumentReferenceExpression ("sender"));
			method.Statements.Add (AddLinePragma (assign, builder));

			assign = new CodeAssignStatement ();
			assign.Left = new CodeVariableReferenceExpression ("Container");
			assign.Right = new CodeCastExpression (containerRef,
						new CodePropertyReferenceExpression (targetExpr, "BindingContainer"));
			method.Statements.Add (AddLinePragma (assign, builder));

			return method;
		}

		void AddDataBindingLiteral (ControlBuilder builder, DataBindingBuilder db)
		{
			if (db.Code == null || db.Code.Trim () == "")
				return;

			EnsureID (db);
			CreateField (db, false);

			string dbMethodName = "__DataBind_" + db.ID;
			// Add the method that builds the DataBoundLiteralControl
			InitMethod (db, false, false);
			CodeMemberMethod method = db.Method;
			AddEventAssign (method, builder, "DataBinding", typeof (EventHandler), dbMethodName);
			method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));

			// Add the DataBind handler
			method = CreateDBMethod (builder, dbMethodName, GetContainerType (builder), typeof (DataBoundLiteralControl));
			builder.DataBindingMethod = method;

			CodeVariableReferenceExpression targetExpr = new CodeVariableReferenceExpression ("target");
			CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
			invoke.Method = new CodeMethodReferenceExpression (targetExpr, "SetDataBoundString");
			invoke.Parameters.Add (new CodePrimitiveExpression (0));

			CodeMethodInvokeExpression tostring = new CodeMethodInvokeExpression ();
			tostring.Method = new CodeMethodReferenceExpression (
							new CodeTypeReferenceExpression (typeof (Convert)),
							"ToString");
			tostring.Parameters.Add (new CodeSnippetExpression (db.Code));
			invoke.Parameters.Add (tostring);
			method.Statements.Add (AddLinePragma (invoke, builder));
			
			mainClass.Members.Add (method);
			
			AddChildCall (builder, db);
		}

		void FlushText (ControlBuilder builder, StringBuilder sb)
		{
			if (sb.Length > 0) {
				AddLiteralSubObject (builder, sb.ToString ());
				sb.Length = 0;
			}
		}

		protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
		{
			EnsureID (builder);
			bool isTemplate = builder.IsTemplate;
			
			if (!isTemplate && !inTemplate) {
				CreateField (builder, true);
			} else if (!isTemplate) {
				bool doCheck = false;				
				bool singleInstance = false;
				ControlBuilder pb = builder.ParentBuilder;
				TemplateBuilder tpb;
				while (pb != null) {
					tpb = pb as TemplateBuilder;
					if (tpb == null) {
						pb = pb.ParentBuilder;
						continue;
					}
					
					if (tpb.TemplateInstance == TemplateInstance.Single)
						singleInstance = true;
					break;
				}
				
				if (!singleInstance)
					builder.ID = builder.GetNextID (null);
				else
					doCheck = true;

				CreateField (builder, doCheck);
			}

			InitMethod (builder, isTemplate, childrenAsProperties);
			if (!isTemplate || builder.GetType () == typeof (RootBuilder))
				CreateAssignStatementsFromAttributes (builder);

			if (builder.Children != null && builder.Children.Count > 0) {
				StringBuilder sb = new StringBuilder ();
				foreach (object b in builder.Children) {
					if (b is string) {
						sb.Append ((string) b);
						continue;
					}

					FlushText (builder, sb);
					if (b is ObjectTagBuilder) {
						ProcessObjectTag ((ObjectTagBuilder) b);
					} else if (b is StringPropertyBuilder) {
						StringPropertyBuilder pb = b as StringPropertyBuilder;
						if (pb.Children != null && pb.Children.Count > 0) {
							StringBuilder asb = new StringBuilder ();
							foreach (string s in pb.Children)
								asb.Append (s);
							CodeMemberMethod method = builder.Method;
							CodeAssignStatement assign = new CodeAssignStatement ();
							assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
							assign.Right = new CodePrimitiveExpression (asb.ToString ());
							method.Statements.Add (AddLinePragma (assign, builder));
						}
					} else if (b is ContentBuilderInternal) {
						ContentBuilderInternal cb = (ContentBuilderInternal) b;
						CreateControlTree (cb, false, true);
						AddContentTemplateInvocation (cb, builder.Method, cb.Method.Name);
						continue;
					}

					// Ignore TemplateBuilders - they are processed in InitMethod
					else if (b is TemplateBuilder) {
					} else if (b is CodeRenderBuilder) {
						AddCodeRender (builder, (CodeRenderBuilder) b);
					} else if (b is DataBindingBuilder) {
						AddDataBindingLiteral (builder, (DataBindingBuilder) b);
					} else if (b is ControlBuilder) {
						ControlBuilder child = (ControlBuilder) b;
						CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
						AddChildCall (builder, child);
						continue;
					} else
						throw new Exception ("???");

					ControlBuilder bldr = b as ControlBuilder;
					bldr.ProcessGeneratedCode (CompileUnit, BaseType, DerivedType, bldr.Method, bldr.DataBindingMethod);
				}

				FlushText (builder, sb);
			}

			ControlBuilder defaultPropertyBuilder = builder.DefaultPropertyBuilder;
			if (defaultPropertyBuilder != null) {
				CreateControlTree (defaultPropertyBuilder, false, true);
				AddChildCall (builder, defaultPropertyBuilder);
			}
			
			if (builder.HasAspCode) {
				CodeMemberMethod renderMethod = builder.RenderMethod;
				CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
				m.TargetObject = thisRef;
				m.MethodName = renderMethod.Name;

				CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
				create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
				create.TargetObject = thisRef;
				create.MethodName = renderMethod.Name;

				CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
				invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
				invoke.Parameters.Add (create);

				builder.MethodStatements.Add (invoke);
			}

			if (builder is RootBuilder)
				if (!String.IsNullOrEmpty (parser.MetaResourceKey))
					AssignPropertiesFromResources (builder, parser.BaseType, parser.MetaResourceKey);
			
			if ((!isTemplate || builder is RootBuilder) && !String.IsNullOrEmpty (builder.GetAttribute ("meta:resourcekey")))
				CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
			
			if ((childrenAsProperties && builder.PropertyBuilderShouldReturnValue) || (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType)))
				builder.Method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));

			builder.ProcessGeneratedCode (CompileUnit, BaseType, DerivedType, builder.Method, builder.DataBindingMethod);
		}

		protected override void AddStatementsToConstructor (CodeConstructor ctor)
		{
			if (masterPageContentPlaceHolders == null || masterPageContentPlaceHolders.Count == 0)
				return;
			
			var ilist = new CodeVariableDeclarationStatement ();
			ilist.Name = "__contentPlaceHolders";
			ilist.Type = new CodeTypeReference (typeof (IList));
			ilist.InitExpression = new CodePropertyReferenceExpression (thisRef, "ContentPlaceHolders");
			
			var ilistRef = new CodeVariableReferenceExpression ("__contentPlaceHolders");
			CodeStatementCollection statements = ctor.Statements;
			statements.Add (ilist);

			CodeMethodInvokeExpression mcall;
			foreach (string id in masterPageContentPlaceHolders) {
				mcall = new CodeMethodInvokeExpression (ilistRef, "Add");
				mcall.Parameters.Add (new CodePrimitiveExpression (id.ToLowerInvariant ()));
				statements.Add (mcall);
			}
		}
		
		protected internal override void CreateMethods ()
		{
			base.CreateMethods ();

			CreateProperties ();
			CreateControlTree (parser.RootBuilder, false, false);
			CreateFrameworkInitializeMethod ();
		}

		protected override void InitializeType ()
		{
			List <string> registeredTagNames = parser.RegisteredTagNames;
			RootBuilder rb = parser.RootBuilder;
			if (rb == null || registeredTagNames == null || registeredTagNames.Count == 0)
				return;

			AspComponent component;
			foreach (string tagName in registeredTagNames) {
				component = rb.Foundry.GetComponent (tagName);
				if (component == null || component.Type == null) // unlikely
					throw new HttpException ("Custom control '" + tagName + "' cannot be found.");
				if (!(typeof (UserControl).IsAssignableFrom (component.Type)))
					throw new ParseException (parser.Location, "Type '" + component.Type.ToString () + "' does not derive from 'System.Web.UI.UserControl'.");
				AddReferencedAssembly (component.Type.Assembly);
			}
		}
		
		void CallBaseFrameworkInitialize (CodeMemberMethod method)
		{
			CodeBaseReferenceExpression baseRef = new CodeBaseReferenceExpression ();
			CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (baseRef, "FrameworkInitialize");
			method.Statements.Add (invoke);
		}
		
		void CallSetStringResourcePointer (CodeMemberMethod method)
		{
			CodeFieldReferenceExpression stringResource = GetMainClassFieldReferenceExpression ("__stringResource");
			method.Statements.Add (
				new CodeMethodInvokeExpression (
					thisRef,
					"SetStringResourcePointer",
					new CodeExpression[] {stringResource, new CodePrimitiveExpression (0)})
			);
		}
		
		void CreateFrameworkInitializeMethod ()
		{
			CodeMemberMethod method = new CodeMemberMethod ();
			method.Name = "FrameworkInitialize";
			method.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			PrependStatementsToFrameworkInitialize (method);
			CallBaseFrameworkInitialize (method);
			CallSetStringResourcePointer (method);
			AppendStatementsToFrameworkInitialize (method);
			mainClass.Members.Add (method);
		}

		protected virtual void PrependStatementsToFrameworkInitialize (CodeMemberMethod method)
		{
		}

		protected virtual void AppendStatementsToFrameworkInitialize (CodeMemberMethod method)
		{
			if (!parser.EnableViewState) {
				CodeAssignStatement stmt = new CodeAssignStatement ();
				stmt.Left = new CodePropertyReferenceExpression (thisRef, "EnableViewState");
				stmt.Right = new CodePrimitiveExpression (false);
				method.Statements.Add (stmt);
			}

			CodeMethodReferenceExpression methodExpr;
			methodExpr = new CodeMethodReferenceExpression (thisRef, "__BuildControlTree");
			CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression (methodExpr, thisRef);
			method.Statements.Add (new CodeExpressionStatement (expr));
		}

		protected override void AddApplicationAndSessionObjects ()
		{
			foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.ApplicationObjects) {
				CreateFieldForObject (tag.Type, tag.ObjectID);
				CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, true, false);
			}

			foreach (ObjectTagBuilder tag in GlobalAsaxCompiler.SessionObjects) {
				CreateApplicationOrSessionPropertyForObject (tag.Type, tag.ObjectID, false, false);
			}
		}

		protected override void CreateStaticFields ()
		{
			base.CreateStaticFields ();

			CodeMemberField fld = new CodeMemberField (typeof (object), "__stringResource");
			fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
			fld.InitExpression = new CodePrimitiveExpression (null);
			mainClass.Members.Add (fld);
		}
		
		protected void ProcessObjectTag (ObjectTagBuilder tag)
		{
			string fieldName = CreateFieldForObject (tag.Type, tag.ObjectID);
			CreatePropertyForObject (tag.Type, tag.ObjectID, fieldName, false);
		}

		void CreateProperties ()
		{
			if (!parser.AutoEventWireup) {
				CreateAutoEventWireup ();
			} else {
				CreateAutoHandlers ();
			}

			CreateApplicationInstance ();
		}
		
		void CreateApplicationInstance ()
		{
			CodeMemberProperty prop = new CodeMemberProperty ();
			Type appType = typeof (HttpApplication);
			prop.Type = new CodeTypeReference (appType);
			prop.Name = "ApplicationInstance";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Final;

			CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression (thisRef, "Context");

			propRef = new CodePropertyReferenceExpression (propRef, "ApplicationInstance");

			CodeCastExpression cast = new CodeCastExpression (appType.FullName, propRef);
			prop.GetStatements.Add (new CodeMethodReturnStatement (cast));
			if (partialClass != null)
				partialClass.Members.Add (prop);
			else
				mainClass.Members.Add (prop);
		}

		void CreateContentPlaceHolderTemplateProperty (string backingField, string name)
		{
			CodeMemberProperty prop = new CodeMemberProperty ();
			prop.Type = new CodeTypeReference (typeof (ITemplate));
			prop.Name = name;
			prop.Attributes = MemberAttributes.Public;

			var ret = new CodeMethodReturnStatement ();
			var fldRef = new CodeFieldReferenceExpression (thisRef, backingField);
			ret.Expression = fldRef;
			prop.GetStatements.Add (ret);
			prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));

			prop.CustomAttributes.Add (new CodeAttributeDeclaration ("TemplateContainer", new CodeAttributeArgument [] {
						new CodeAttributeArgument (new CodeTypeOfExpression (new CodeTypeReference (typeof (MasterPage))))
					}
				)
			);

			var enumValueRef = new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (typeof (TemplateInstance)), "Single");
			prop.CustomAttributes.Add (new CodeAttributeDeclaration ("TemplateInstanceAttribute", new CodeAttributeArgument [] {
						new CodeAttributeArgument (enumValueRef)
					}
				)
			);

			mainClass.Members.Add (prop);
		}
		
		void CreateAutoHandlers ()
		{
			// Create AutoHandlers property
			CodeMemberProperty prop = new CodeMemberProperty ();
			prop.Type = new CodeTypeReference (typeof (int));
			prop.Name = "AutoHandlers";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			
			CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
			CodeFieldReferenceExpression fldRef ;
			fldRef = new CodeFieldReferenceExpression (mainClassExpr, "__autoHandlers");
			ret.Expression = fldRef;
			prop.GetStatements.Add (ret);
			prop.SetStatements.Add (new CodeAssignStatement (fldRef, new CodePropertySetValueReferenceExpression ()));

			CodeAttributeDeclaration attr = new CodeAttributeDeclaration ("System.Obsolete");
			prop.CustomAttributes.Add (attr);			
			mainClass.Members.Add (prop);

			// Add the __autoHandlers field
			CodeMemberField fld = new CodeMemberField (typeof (int), "__autoHandlers");
			fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
			mainClass.Members.Add (fld);
		}

		void CreateAutoEventWireup ()
		{
			// The getter returns false
			CodeMemberProperty prop = new CodeMemberProperty ();
			prop.Type = new CodeTypeReference (typeof (bool));
			prop.Name = "SupportAutoEvents";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			prop.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false)));
			mainClass.Members.Add (prop);
		}

		protected virtual string HandleUrlProperty (string str, MemberInfo member)
		{
			return str;
		}

		TypeConverter GetConverterForMember (MemberInfo member)
		{
			TypeDescriptionProvider prov = TypeDescriptor.GetProvider (member.ReflectedType);
			if (prov == null)
				return null;

			ICustomTypeDescriptor desc = prov.GetTypeDescriptor (member.ReflectedType);
			PropertyDescriptorCollection coll = desc != null ? desc.GetProperties () : null;

			if (coll == null || coll.Count == 0)
				return null;

			PropertyDescriptor pd = coll.Find (member.Name, false);
			if (pd == null)
				return null;

			return pd.Converter;
		}
		
		CodeExpression CreateNullableExpression (Type type, CodeExpression inst, bool nullable)
		{
			if (!nullable)
				return inst;
			
			return new CodeObjectCreateExpression (type, new CodeExpression[] {inst});
		}

		bool SafeCanConvertFrom (Type type, TypeConverter cvt)
		{
			try {
				return cvt.CanConvertFrom (type);
			} catch (NotImplementedException) {
				return false;
			}
		}

		bool SafeCanConvertTo (Type type, TypeConverter cvt)
		{
			try {
				return cvt.CanConvertTo (type);
			} catch (NotImplementedException) {
				return false;
			}
		}
		
		CodeExpression GetExpressionFromString (Type type, string str, MemberInfo member)
		{
			TypeConverter cvt = GetConverterForMember (member);
			if (cvt != null && !SafeCanConvertFrom (typeof (string), cvt))
				cvt = null;
			
			object convertedFromAttr = null;
			bool preConverted = false;
			if (cvt != null && str != null) {
				convertedFromAttr = cvt.ConvertFromInvariantString (str);
				if (convertedFromAttr != null) {
					type = convertedFromAttr.GetType ();
					preConverted = true;
				}
			}

			bool wasNullable = false;
			Type originalType = type;

			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
				Type[] types = type.GetGenericArguments();
				originalType = type;
				type = types[0]; // we're interested only in the first type here
				wasNullable = true;
			}

			if (type == typeof (string)) {
				object[] urlAttr = member.GetCustomAttributes (typeof (UrlPropertyAttribute), true);
				if (urlAttr.Length != 0)
					str = HandleUrlProperty ((preConverted && convertedFromAttr is string) ? (string)convertedFromAttr : str, member);
				else if (preConverted)
					return CreateNullableExpression (originalType,
									 new CodePrimitiveExpression ((string) convertedFromAttr),
									 wasNullable);

				return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
			} else if (type == typeof (bool)) {
				if (preConverted)
					return CreateNullableExpression (originalType,
									 new CodePrimitiveExpression ((bool) convertedFromAttr),
									 wasNullable);
				
				if (str == null || str == "" || InvariantCompareNoCase (str, "true"))
					return CreateNullableExpression (originalType, new CodePrimitiveExpression (true), wasNullable);
				else if (InvariantCompareNoCase (str, "false"))
					return CreateNullableExpression (originalType, new CodePrimitiveExpression (false), wasNullable);
				else if (wasNullable && InvariantCompareNoCase(str, "null"))
					return new CodePrimitiveExpression (null);
				else
					throw new ParseException (currentLocation,
							"Value '" + str  + "' is not a valid boolean.");
			} else if (type == monoTypeType)
				type = typeof (System.Type);
			
			if (str == null)
				return new CodePrimitiveExpression (null);

			if (type.IsPrimitive)
				return CreateNullableExpression (originalType,
								 new CodePrimitiveExpression (
									 Convert.ChangeType (preConverted ? convertedFromAttr : str,
											     type, Helpers.InvariantCulture)),
								 wasNullable);

			if (type == typeof (string [])) {
				string [] subs;

				if (preConverted)
					subs = (string[])convertedFromAttr;
				else
					subs = str.Split (',');
				CodeArrayCreateExpression expr = new CodeArrayCreateExpression ();
				expr.CreateType = new CodeTypeReference (typeof (string));
				foreach (string v in subs)
					expr.Initializers.Add (new CodePrimitiveExpression (v.Trim ()));

				return CreateNullableExpression (originalType, expr, wasNullable);
			}
			
			if (type == typeof (Color)) {
				Color c;
				
				if (!preConverted) {
					if (colorConverter == null)
						colorConverter = TypeDescriptor.GetConverter (typeof (Color));
				
					if (str.Trim().Length == 0) {
						CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (typeof (Color));
						return CreateNullableExpression (originalType,
										 new CodeFieldReferenceExpression (ft, "Empty"),
										 wasNullable);
					}

					try {
						if (str.IndexOf (',') == -1) {
							c = (Color) colorConverter.ConvertFromString (str);
						} else {
							int [] argb = new int [4];
							argb [0] = 255;

							string [] parts = str.Split (',');
							int length = parts.Length;
							if (length < 3)
								throw new Exception ();

							int basei = (length == 4) ? 0 : 1;
							for (int i = length - 1; i >= 0; i--) {
								argb [basei + i] = (int) Byte.Parse (parts [i]);
							}
							c = Color.FromArgb (argb [0], argb [1], argb [2], argb [3]);
						}
					} catch (Exception e) {
						// Hack: "LightGrey" is accepted, but only for ASP.NET, as the
						// TypeConverter for Color fails to ConvertFromString.
						// Hence this hack...
						if (InvariantCompareNoCase ("LightGrey", str)) {
							c = Color.LightGray;
						} else {
							throw new ParseException (currentLocation,
										  "Color " + str + " is not a valid color.", e);
						}
					}
				} else
					c = (Color)convertedFromAttr;
				
				if (c.IsKnownColor) {
					CodeFieldReferenceExpression expr = new CodeFieldReferenceExpression ();
					if (c.IsSystemColor)
						type = typeof (SystemColors);

					expr.TargetObject = new CodeTypeReferenceExpression (type);
					expr.FieldName = c.Name;
					return CreateNullableExpression (originalType, expr, wasNullable);
				} else {
					CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
					m.TargetObject = new CodeTypeReferenceExpression (type);
					m.MethodName = "FromArgb";
					CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
					invoke.Parameters.Add (new CodePrimitiveExpression (c.A));
					invoke.Parameters.Add (new CodePrimitiveExpression (c.R));
					invoke.Parameters.Add (new CodePrimitiveExpression (c.G));
					invoke.Parameters.Add (new CodePrimitiveExpression (c.B));
					return CreateNullableExpression (originalType, invoke, wasNullable);
				}
			}

			TypeConverter converter = preConverted ? cvt : wasNullable ? TypeDescriptor.GetConverter (type) : null;
			if (converter == null) {
				PropertyDescriptor pdesc = TypeDescriptor.GetProperties (member.DeclaringType) [member.Name];
				if (pdesc != null)
					converter = pdesc.Converter;
				else {
					Type memberType;
					switch (member.MemberType) {
						case MemberTypes.Field:
							memberType = ((FieldInfo)member).FieldType;
							break;

						case MemberTypes.Property:
							memberType = ((PropertyInfo)member).PropertyType;
							break;

						default:
							memberType = null;
							break;
					}

					if (memberType == null)
						return null;

					converter = TypeDescriptor.GetConverter (memberType);
				}
			}
			
			if (preConverted || (converter != null && SafeCanConvertFrom (typeof (string), converter))) {
				object value = preConverted ? convertedFromAttr : converter.ConvertFromInvariantString (str);

				if (SafeCanConvertTo (typeof (InstanceDescriptor), converter)) {
					InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
					if (wasNullable)
						return CreateNullableExpression (originalType, GenerateInstance (idesc, true),
										 wasNullable);

					CodeExpression instance = GenerateInstance (idesc, true);
					if (type.IsPublic)
						return new CodeCastExpression (type, instance);
					else
						return instance;
				}

				CodeExpression exp = GenerateObjectInstance (value, false);
				if (exp != null)
					return CreateNullableExpression (originalType, exp, wasNullable);
				
				CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
				m.TargetObject = new CodeTypeReferenceExpression (typeof (TypeDescriptor));
				m.MethodName = "GetConverter";
				CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (m);
				CodeTypeReference tref = new CodeTypeReference (type);
				invoke.Parameters.Add (new CodeTypeOfExpression (tref));
				
				invoke = new CodeMethodInvokeExpression (invoke, "ConvertFrom");
				invoke.Parameters.Add (new CodePrimitiveExpression (str));

				if (wasNullable)
					return CreateNullableExpression (originalType, invoke, wasNullable);

				return new CodeCastExpression (type, invoke);
			}

			Console.WriteLine ("Unknown type: " + type + " value: " + str);
			
			return CreateNullableExpression (originalType, new CodePrimitiveExpression (str), wasNullable);
		}
		
		CodeExpression GenerateInstance (InstanceDescriptor idesc, bool throwOnError)
		{
			CodeExpression[] parameters = new CodeExpression [idesc.Arguments.Count];
			int n = 0;
			foreach (object ob in idesc.Arguments) {
				CodeExpression exp = GenerateObjectInstance (ob, throwOnError);
				if (exp == null) return null;
				parameters [n++] = exp;
			}
			
			switch (idesc.MemberInfo.MemberType) {
			case MemberTypes.Constructor:
				CodeTypeReference tob = new CodeTypeReference (idesc.MemberInfo.DeclaringType);
				return new CodeObjectCreateExpression (tob, parameters);

			case MemberTypes.Method:
				CodeTypeReferenceExpression mt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
				return new CodeMethodInvokeExpression (mt, idesc.MemberInfo.Name, parameters);

			case MemberTypes.Field:
				CodeTypeReferenceExpression ft = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
				return new CodeFieldReferenceExpression (ft, idesc.MemberInfo.Name);

			case MemberTypes.Property:
				CodeTypeReferenceExpression pt = new CodeTypeReferenceExpression (idesc.MemberInfo.DeclaringType);
				return new CodePropertyReferenceExpression (pt, idesc.MemberInfo.Name);
			}
			throw new ParseException (currentLocation, "Invalid instance type.");
		}
		
		CodeExpression GenerateObjectInstance (object value, bool throwOnError)
		{
			if (value == null)
				return new CodePrimitiveExpression (null);

			if (value is System.Type) {
				CodeTypeReference tref = new CodeTypeReference (value.ToString ());
				return new CodeTypeOfExpression (tref);
			}
			
			Type t = value.GetType ();

			if (t.IsPrimitive || value is string)
				return new CodePrimitiveExpression (value);
			
			if (t.IsArray) {
				Array ar = (Array) value;
				CodeExpression[] items = new CodeExpression [ar.Length];
				for (int n=0; n<ar.Length; n++) {
					CodeExpression exp = GenerateObjectInstance (ar.GetValue (n), throwOnError);
					if (exp == null) return null; 
					items [n] = exp;
				}
				return new CodeArrayCreateExpression (new CodeTypeReference (t), items);
			}
			
			TypeConverter converter = TypeDescriptor.GetConverter (t);
			if (converter != null && converter.CanConvertTo (typeof (InstanceDescriptor))) {
				InstanceDescriptor idesc = (InstanceDescriptor) converter.ConvertTo (value, typeof(InstanceDescriptor));
				return GenerateInstance (idesc, throwOnError);
			}
			
			InstanceDescriptor desc = GetDefaultInstanceDescriptor (value);
			if (desc != null) return GenerateInstance (desc, throwOnError);
			
			if (throwOnError)
				throw new ParseException (currentLocation, "Cannot generate an instance for the type: " + t);
			else
				return null;
		}
		
		InstanceDescriptor GetDefaultInstanceDescriptor (object value)
		{
			if (value is System.Web.UI.WebControls.Unit) {
				System.Web.UI.WebControls.Unit s = (System.Web.UI.WebControls.Unit) value;
				if (s.IsEmpty) {
					FieldInfo f = typeof (Unit).GetField ("Empty");
					return new InstanceDescriptor (f, null);
				}
				ConstructorInfo c = typeof(System.Web.UI.WebControls.Unit).GetConstructor (
					BindingFlags.Instance | BindingFlags.Public,
					null,
					new Type[] {typeof(double), typeof(System.Web.UI.WebControls.UnitType)},
					null);
				
				return new InstanceDescriptor (c, new object[] {s.Value, s.Type});
			}
			
			if (value is System.Web.UI.WebControls.FontUnit) {
				System.Web.UI.WebControls.FontUnit s = (System.Web.UI.WebControls.FontUnit) value;
				if (s.IsEmpty) {
					FieldInfo f = typeof (FontUnit).GetField ("Empty");
					return new InstanceDescriptor (f, null);
				}

				Type cParamType = null;
				object cParam = null;

				switch (s.Type) {
					case FontSize.AsUnit:
					case FontSize.NotSet:
						cParamType = typeof (System.Web.UI.WebControls.Unit);
						cParam = s.Unit;
						break;

					default:
						cParamType = typeof (string);
						cParam = s.Type.ToString ();
						break;
				}
				
				ConstructorInfo c = typeof(System.Web.UI.WebControls.FontUnit).GetConstructor (
					BindingFlags.Instance | BindingFlags.Public,
					null,
					new Type[] {cParamType},
					null);
				if (c != null)
					return new InstanceDescriptor (c, new object[] {cParam});
			}
			return null;
		}

#if DEBUG
		CodeMethodInvokeExpression CreateConsoleWriteLineCall (string format, params CodeExpression[] parms)
		{
			CodeMethodReferenceExpression cwl = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (System.Console)), "WriteLine");
			CodeMethodInvokeExpression cwlCall = new CodeMethodInvokeExpression (cwl);

			cwlCall.Parameters.Add (new CodePrimitiveExpression (format));
			if (parms != null && parms.Length > 0)
				foreach (CodeExpression expr in parms)
					cwlCall.Parameters.Add (expr);

			return cwlCall;
		}
#endif
	}
}