File: TemplateParser.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (1289 lines) | stat: -rw-r--r-- 35,574 bytes parent folder | download | duplicates (7)
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
//
// System.Web.UI.TemplateParser
//
// Authors:
//	Duncan Mak (duncan@ximian.com)
//	Gonzalo Paniagua Javier (gonzalo@ximian.com)
//      Marek Habersack (mhabersack@novell.com)
//
// (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
// Copyright (C) 2005-2008 Novell, Inc (http://www.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.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Web.Compilation;
using System.Web.Hosting;
using System.Web.Configuration;
using System.Web.Util;

namespace System.Web.UI {
	internal class ServerSideScript
	{
		public readonly string Script;
		public readonly ILocation Location;
		
		public ServerSideScript (string script, ILocation location)
		{
			Script = script;
			Location = location;
		}
	}
	
	// CAS
	[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	[AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	public abstract class TemplateParser : BaseParser
	{
		[Flags]
		internal enum OutputCacheParsedParams
		{
			Location               = 0x0001,
			CacheProfile           = 0x0002,
			NoStore                = 0x0004,
			SqlDependency          = 0x0008,
			VaryByCustom           = 0x0010,
			VaryByHeader           = 0x0020,
			VaryByControl          = 0x0040,
			VaryByContentEncodings = 0x0080
		}
		
		string inputFile;
		string text;
		IDictionary mainAttributes;
		List <string> dependencies;
		List <string> assemblies;
		IDictionary anames;
		string[] binDirAssemblies;
		Dictionary <string, bool> namespacesCache;
		Dictionary <string, bool> imports;
		List <string> interfaces;
		List <ServerSideScript> scripts;
		Type baseType;
		bool baseTypeIsGlobal = true;
		string className;
		RootBuilder rootBuilder;
		bool debug;
		string compilerOptions;
		string language;
		bool implicitLanguage;
		bool strictOn ;
		bool explicitOn;
		bool linePragmasOn = true;
		bool output_cache;
		int oc_duration;
		string oc_header, oc_custom, oc_param, oc_controls;
		string oc_content_encodings, oc_cacheprofile, oc_sqldependency;
		bool oc_nostore;
		OutputCacheParsedParams oc_parsed_params = 0;
		bool oc_shared;
		OutputCacheLocation oc_location;

		// Kludge needed to support pre-parsing of the main directive (see
		// AspNetGenerator.GetRootBuilderType)
		internal int allowedMainDirectives = 0;
		
		byte[] md5checksum;
		string src;
		bool srcIsLegacy;
		string partialClassName;
		string codeFileBaseClass;
		string metaResourceKey;
		Type codeFileBaseClassType;
		Type pageParserFilterType;
		PageParserFilter pageParserFilter;
		
		List <UnknownAttributeDescriptor> unknownMainAttributes;
		Stack <string> includeDirs;
		List <string> registeredTagNames;
		ILocation directiveLocation;
		
		int appAssemblyIndex = -1;

		internal TemplateParser ()
		{
			imports = new Dictionary <string, bool> (StringComparer.Ordinal);
			LoadConfigDefaults ();
			assemblies = new List <string> ();
			CompilationSection compConfig = CompilationConfig;
			foreach (AssemblyInfo info in compConfig.Assemblies) {
				if (info.Assembly != "*")
					AddAssemblyByName (info.Assembly);
			}

			language = compConfig.DefaultLanguage;
			implicitLanguage = true;
		}

		internal virtual void LoadConfigDefaults ()
		{
			AddNamespaces (imports);
			debug = CompilationConfig.Debug;
		}
		
		internal void AddApplicationAssembly ()
		{
			if (Context.ApplicationInstance == null)
                                return; // this may happen if we have Global.asax and have
                                        // controls registered from Web.Config
			string location = Context.ApplicationInstance.AssemblyLocation;
			if (location != typeof (TemplateParser).Assembly.Location) {
				 assemblies.Add (location);
				 appAssemblyIndex = assemblies.Count - 1;
			}
		}

		internal abstract Type CompileIntoType ();

		internal void AddControl (Type type, IDictionary attributes)
		{
			AspGenerator generator = AspGenerator;
			if (generator == null)
				return;
			generator.AddControl (type, attributes);
		}
		
		void AddNamespaces (Dictionary <string, bool> imports)
		{
			if (BuildManager.HaveResources)
				imports.Add ("System.Resources", true);
			
			PagesSection pages = PagesConfig;
			if (pages == null)
				return;

			NamespaceCollection namespaces = pages.Namespaces;
			if (namespaces == null || namespaces.Count == 0)
				return;
			
			foreach (NamespaceInfo nsi in namespaces) {
				string ns = nsi.Namespace;
				if (imports.ContainsKey (ns))
					continue;
				
				imports.Add (ns, true);
			}
		}
		
		internal void RegisterCustomControl (string tagPrefix, string tagName, string src)
                {
                        string realpath = null;
			bool fileExists = false;
			VirtualFile vf = null;
			VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
			VirtualPath vp = new VirtualPath (src, BaseVirtualDir);
			string vpAbsolute = vpp.CombineVirtualPaths (VirtualPath.Absolute, vp.Absolute);
			
			if (vpp.FileExists (vpAbsolute)) {
				fileExists = true;
				vf = vpp.GetFile (vpAbsolute);
				if (vf != null)
					realpath = MapPath (vf.VirtualPath);
			}

			if (!fileExists)
				ThrowParseFileNotFound (src);

			if (String.Compare (realpath, inputFile, StringComparison.Ordinal) == 0)
                                return;
			
			string vpath = vf.VirtualPath;
                        
                        try {
				RegisterTagName (tagPrefix + ":" + tagName);
				RootBuilder.Foundry.RegisterFoundry (tagPrefix, tagName, vpath);
				AddDependency (vpath);
                        } catch (ParseException pe) {
                                if (this is UserControlParser)
                                        throw new ParseException (Location, pe.Message, pe);
                                throw;
                        }
                }

                internal void RegisterNamespace (string tagPrefix, string ns, string assembly)
                {
                        AddImport (ns);
                        Assembly ass = null;
			
			if (assembly != null && assembly.Length > 0)
				ass = AddAssemblyByName (assembly);
			
                        RootBuilder.Foundry.RegisterFoundry (tagPrefix, ass, ns);
                }

		internal virtual void HandleOptions (object obj)
		{
		}

		internal static string GetOneKey (IDictionary tbl)
		{
			foreach (object key in tbl.Keys)
				return key.ToString ();

			return null;
		}
		
		internal virtual void AddDirective (string directive, IDictionary atts)
		{
			var pageParserFilter = PageParserFilter;
			if (String.Compare (directive, DefaultDirectiveName, true, Helpers.InvariantCulture) == 0) {
				bool allowMainDirective = allowedMainDirectives > 0;
				
				if (mainAttributes != null && !allowMainDirective)
					ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");

				allowedMainDirectives--;
				if (mainAttributes != null)
					return;
				
				if (pageParserFilter != null)
					pageParserFilter.PreprocessDirective (directive.ToLower (Helpers.InvariantCulture), atts);
				
				mainAttributes = atts;
				ProcessMainAttributes (mainAttributes);
				return;
			} else if (pageParserFilter != null)
				pageParserFilter.PreprocessDirective (directive.ToLower (Helpers.InvariantCulture), atts);
				
			int cmp = String.Compare ("Assembly", directive, true, Helpers.InvariantCulture);
			if (cmp == 0) {
				string name = GetString (atts, "Name", null);
				string src = GetString (atts, "Src", null);

				if (atts.Count > 0)
					ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");

				if (name == null && src == null)
					ThrowParseException ("You gotta specify Src or Name");
					
				if (name != null && src != null)
					ThrowParseException ("Src and Name cannot be used together");

				if (name != null) {
					AddAssemblyByName (name);
				} else {
					GetAssemblyFromSource (src);
				}

				return;
			}

			cmp = String.Compare ("Import", directive, true, Helpers.InvariantCulture);
			if (cmp == 0) {
				string namesp = GetString (atts, "Namespace", null);
				if (atts.Count > 0)
					ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
				
				AddImport (namesp);
				return;
			}

			cmp = String.Compare ("Implements", directive, true, Helpers.InvariantCulture);
			if (cmp == 0) {
				string ifacename = GetString (atts, "Interface", "");

				if (atts.Count > 0)
					ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
				
				Type iface = LoadType (ifacename);
				if (iface == null)
					ThrowParseException ("Cannot find type " + ifacename);

				if (!iface.IsInterface)
					ThrowParseException (iface + " is not an interface");

				AddInterface (iface.FullName);
				return;
			}

			cmp = String.Compare ("OutputCache", directive, true, Helpers.InvariantCulture);
			if (cmp == 0) {
				HttpResponse response = HttpContext.Current.Response;
				if (response != null)
					response.Cache.SetValidUntilExpires (true);
				
				output_cache = true;
				ProcessOutputCacheAttributes (atts);
				return;
			}

			ThrowParseException ("Unknown directive: " + directive);
		}

		internal virtual void ProcessOutputCacheAttributes (IDictionary atts)
		{
			if (atts ["Duration"] == null)
				ThrowParseException ("The directive is missing a 'duration' attribute.");
			if (atts ["VaryByParam"] == null && atts ["VaryByControl"] == null)
				ThrowParseException ("This directive is missing 'VaryByParam' " +
						     "or 'VaryByControl' attribute, which should be set to \"none\", \"*\", " +
						     "or a list of name/value pairs.");

			foreach (DictionaryEntry entry in atts) {
				string key = (string) entry.Key;
				if (key == null)
					continue;
					
				switch (key.ToLower (Helpers.InvariantCulture)) {
					case "duration":
						oc_duration = Int32.Parse ((string) entry.Value);
						if (oc_duration < 1)
							ThrowParseException ("The 'duration' attribute must be set " +
									     "to a positive integer value");
						break;

					case "sqldependency":
						oc_sqldependency = (string) entry.Value;
						break;
							
					case "nostore":
						try {
							oc_nostore = Boolean.Parse ((string) entry.Value);
							oc_parsed_params |= OutputCacheParsedParams.NoStore;
						} catch {
							ThrowParseException ("The 'NoStore' attribute is case sensitive" +
									     " and must be set to 'true' or 'false'.");
						}
						break;

					case "cacheprofile":
						oc_cacheprofile = (string) entry.Value;
						oc_parsed_params |= OutputCacheParsedParams.CacheProfile;
						break;
							
					case "varybycontentencodings":
						oc_content_encodings = (string) entry.Value;
						oc_parsed_params |= OutputCacheParsedParams.VaryByContentEncodings;
						break;

					case "varybyparam":
						oc_param = (string) entry.Value;
						if (String.Compare (oc_param, "none", true, Helpers.InvariantCulture) == 0)
							oc_param = null;
						break;
					case "varybyheader":
						oc_header = (string) entry.Value;
						oc_parsed_params |= OutputCacheParsedParams.VaryByHeader;
						break;
					case "varybycustom":
						oc_custom = (string) entry.Value;
						oc_parsed_params |= OutputCacheParsedParams.VaryByCustom;
						break;
					case "location":
						if (!(this is PageParser))
							goto default;
						
						try {
							oc_location = (OutputCacheLocation) Enum.Parse (
								typeof (OutputCacheLocation), (string) entry.Value, true);
							oc_parsed_params |= OutputCacheParsedParams.Location;
						} catch {
							ThrowParseException ("The 'location' attribute is case sensitive and " +
									     "must be one of the following values: Any, Client, " +
									     "Downstream, Server, None, ServerAndClient.");
						}
						break;
					case "varybycontrol":
						oc_controls = (string) entry.Value;
						oc_parsed_params |= OutputCacheParsedParams.VaryByControl;
						break;
					case "shared":
						if (this is PageParser)
							goto default;

						try {
							oc_shared = Boolean.Parse ((string) entry.Value);
						} catch {
							ThrowParseException ("The 'shared' attribute is case sensitive" +
									     " and must be set to 'true' or 'false'.");
						}
						break;
					default:
						ThrowParseException ("The '" + key + "' attribute is not " +
								     "supported by the 'Outputcache' directive.");
						break;
				}
					
			}
		}
		
		internal Type LoadType (string typeName)
		{
			Type type = HttpApplication.LoadType (typeName);
			if (type == null)
				return null;
			Assembly asm = type.Assembly;
			string location = asm.Location;
			
			string dirname = Path.GetDirectoryName (location);
			bool doAddAssembly = true;
			if (dirname == HttpApplication.BinDirectory)
				doAddAssembly = false;

			if (doAddAssembly)
				AddAssembly (asm, true);

			return type;
		}

		internal virtual void AddInterface (string iface)
		{
			if (interfaces == null)
				interfaces = new List <string> ();

			if (!interfaces.Contains (iface))
				interfaces.Add (iface);
		}
		
		internal virtual void AddImport (string namesp)
		{
			if (namesp == null || namesp.Length == 0)
				return;
			
			if (imports == null)
				imports = new Dictionary <string, bool> (StringComparer.Ordinal);
			
			if (imports.ContainsKey (namesp))
				return;
			
			imports.Add (namesp, true);
			AddAssemblyForNamespace (namesp);
		}

		void AddAssemblyForNamespace (string namesp)
		{
			if (binDirAssemblies == null)
				binDirAssemblies = HttpApplication.BinDirectoryAssemblies;
			if (binDirAssemblies.Length == 0)
				return;

			if (namespacesCache == null)
				namespacesCache = new Dictionary <string, bool> ();
			else if (namespacesCache.ContainsKey (namesp))
				return;
			
			foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ())
				if (FindNamespaceInAssembly (asm, namesp))
					return;
			
			IList tla = BuildManager.TopLevelAssemblies;
			if (tla != null && tla.Count > 0) {
				foreach (Assembly asm in tla) {
					if (FindNamespaceInAssembly (asm, namesp))
						return;
				}
			}

			Assembly a;
			foreach (string s in binDirAssemblies) {
				a = Assembly.LoadFrom (s);
				if (FindNamespaceInAssembly (a, namesp))
					return;
			}
		}

		bool FindNamespaceInAssembly (Assembly asm, string namesp)
		{
			Type[] asmTypes;

			try {
				asmTypes = asm.GetTypes ();
			} catch (ReflectionTypeLoadException) {
				// ignore
				return false;
			}
			
			foreach (Type type in asmTypes) {
				if (String.Compare (type.Namespace, namesp, StringComparison.Ordinal) == 0) {
					namespacesCache.Add (namesp, true);
					AddAssembly (asm, true);
					return true;
				}
			}

			return false;
		}
		
		internal virtual void AddSourceDependency (string filename)
		{
			if (dependencies != null && dependencies.Contains (filename))
				ThrowParseException ("Circular file references are not allowed. File: " + filename);

			AddDependency (filename);
		}

		internal virtual void AddDependency (string filename)
		{
			AddDependency (filename, true);
		}
		
		internal virtual void AddDependency (string filename, bool combinePaths)
		{
			if (String.IsNullOrEmpty (filename))
				return;

			if (dependencies == null)
				dependencies = new List <string> ();

			if (combinePaths)
				filename = HostingEnvironment.VirtualPathProvider.CombineVirtualPaths (VirtualPath.Absolute, filename);

			if (!dependencies.Contains (filename))
				dependencies.Add (filename);
		}
		
		internal virtual void AddAssembly (Assembly assembly, bool fullPath)
		{
			if (assembly == null || assembly.Location == String.Empty)
				return;

			if (anames == null)
				anames = new Dictionary <string, object> ();

			string name = assembly.GetName ().Name;
			string loc = assembly.Location;
			if (fullPath) {
				if (!assemblies.Contains (loc)) {
					assemblies.Add (loc);
				}

				anames [name] = loc;
				anames [loc] = assembly;
			} else {
				if (!assemblies.Contains (name)) {
					assemblies.Add (name);
				}

				anames [name] = assembly;
			}
		}

		internal virtual Assembly AddAssemblyByFileName (string filename)
		{
			Assembly assembly = null;
			Exception error = null;

			try {
				assembly = Assembly.LoadFrom (filename);
			} catch (Exception e) { error = e; }

			if (assembly == null)
				ThrowParseException ("Assembly " + filename + " not found", error);

			AddAssembly (assembly, true);
			return assembly;
		}

		internal virtual Assembly AddAssemblyByName (string name)
		{
			if (anames == null)
				anames = new Dictionary <string, object> ();

			if (anames.Contains (name)) {
				object o = anames [name];
				if (o is string)
					o = anames [o];

				return (Assembly) o;
			}

			Assembly assembly = null;
			Exception error = null;
			try {
				assembly = Assembly.Load (name);
			} catch (Exception e) { error = e; }

			if (assembly == null) {
				try {
					assembly = Assembly.LoadWithPartialName (name);
				} catch (Exception e) { error = e; }
			}
			
			if (assembly == null)
				ThrowParseException ("Assembly " + name + " not found", error);

			AddAssembly (assembly, true);
			return assembly;
		}
		
		internal virtual void ProcessMainAttributes (IDictionary atts)
		{
			directiveLocation = new System.Web.Compilation.Location (Location);
			CompilationSection compConfig;

			compConfig = CompilationConfig;
			
			atts.Remove ("Description"); // ignored
			atts.Remove ("CodeBehind");  // ignored
			atts.Remove ("AspCompat"); // ignored
			
			debug = GetBool (atts, "Debug", compConfig.Debug);
			compilerOptions = GetString (atts, "CompilerOptions", String.Empty);
			language = GetString (atts, "Language", "");
			if (language.Length != 0)
				implicitLanguage = false;
			else
				language = compConfig.DefaultLanguage;
			
			strictOn = GetBool (atts, "Strict", compConfig.Strict);
			explicitOn = GetBool (atts, "Explicit", compConfig.Explicit);
			if (atts.Contains ("LinePragmas"))
				linePragmasOn = GetBool (atts, "LinePragmas", true);

			string inherits = GetString (atts, "Inherits", null);
			string srcRealPath = null;
			
			// In ASP 2+, the source file is actually integrated with
			// the generated file via the use of partial classes. This
			// means that the code file has to be confirmed, but not
			// used at this point.
			src = GetString (atts, "CodeFile", null);
			codeFileBaseClass = GetString (atts, "CodeFileBaseClass", null);

			if (src == null && codeFileBaseClass != null)
				ThrowParseException ("The 'CodeFileBaseClass' attribute cannot be used without a 'CodeFile' attribute");

			string legacySrc = GetString (atts, "Src", null);
			var vpp = HostingEnvironment.VirtualPathProvider;
			if (legacySrc != null) {
				legacySrc = vpp.CombineVirtualPaths (BaseVirtualDir, legacySrc);
				GetAssemblyFromSource (legacySrc);

				if (src == null) {
					src = legacySrc;
					legacySrc = MapPath (legacySrc, false);
					srcRealPath = legacySrc;
					if (!File.Exists (srcRealPath))
						ThrowParseException ("File " + src + " not found");
					
					srcIsLegacy = true;
				} else 
					legacySrc = MapPath (legacySrc, false);				

				AddDependency (legacySrc, false);
			}
			
			if (!srcIsLegacy && src != null && inherits != null) {
				// Make sure the source exists
				src = vpp.CombineVirtualPaths (BaseVirtualDir, src);
				srcRealPath = MapPath (src, false);

				if (!vpp.FileExists (src))
					ThrowParseException ("File " + src + " not found");

				// We are going to create a partial class that shares
				// the same name as the inherits tag, so reset the
				// name. The base type is changed because it is the
				// code file's responsibilty to extend the classes
				// needed.
				partialClassName = inherits;

				// Add the code file as an option to the
				// compiler. This lets both files be compiled at once.
				compilerOptions += " \"" + srcRealPath + "\"";

				if (codeFileBaseClass != null) {
					try {
						codeFileBaseClassType = LoadType (codeFileBaseClass);
					} catch (Exception) {
					}

					if (codeFileBaseClassType == null)
						ThrowParseException ("Could not load type '{0}'", codeFileBaseClass);
				}
			} else if (inherits != null) {
				// We just set the inherits directly because this is a
				// Single-Page model.
				SetBaseType (inherits);
			}

			if (src != null) {
				if (VirtualPathUtility.IsAbsolute (src))
					src = VirtualPathUtility.ToAppRelative (src);
				AddDependency (src, false);
			}
			
			className = GetString (atts, "ClassName", null);
			if (className != null) {
				string [] identifiers = className.Split ('.');
				for (int i = 0; i < identifiers.Length; i++)
					if (!CodeGenerator.IsValidLanguageIndependentIdentifier (identifiers [i]))
						ThrowParseException (String.Format ("'{0}' is not a valid "
							+ "value for attribute 'classname'.", className));
			}

			if (this is TemplateControlParser)
				metaResourceKey = GetString (atts, "meta:resourcekey", null);
			
			if (inherits != null && (this is PageParser || this is UserControlParser) && atts.Count > 0) {
				if (unknownMainAttributes == null)
					unknownMainAttributes = new List <UnknownAttributeDescriptor> ();
				string key, val;
				
				foreach (DictionaryEntry de in atts) {
					key = de.Key as string;
					val = de.Value as string;
					
					if (String.IsNullOrEmpty (key) || String.IsNullOrEmpty (val))
						continue;
					CheckUnknownAttribute (key, val, inherits);
				}
				return;
			}

			if (atts.Count > 0)
				ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
		}

		void RegisterTagName (string tagName)
		{
			if (registeredTagNames == null)
				registeredTagNames = new List <string> ();

			if (registeredTagNames.Contains (tagName))
				return;

			registeredTagNames.Add (tagName);
		}
		
		void CheckUnknownAttribute (string name, string val, string inherits)
		{
			MemberInfo mi = null;
			bool missing = false;
			string memberName = name.Trim ().ToLower (Helpers.InvariantCulture);
			Type parent = codeFileBaseClassType;

			if (parent == null)
				parent = baseType;
			
			try {
				MemberInfo[] infos = parent.GetMember (memberName,
								       MemberTypes.Field | MemberTypes.Property,
								       BindingFlags.Public | BindingFlags.Instance |
								       BindingFlags.IgnoreCase | BindingFlags.Static);
				if (infos.Length != 0) {
					// prefer public properties to public methods (it's what MS.NET does)
					foreach (MemberInfo tmp in infos) {
						if (tmp is PropertyInfo) {
							mi = tmp;
							break;
						}
					}
					if (mi == null)
						mi = infos [0];
				} else
					missing = true;
			} catch (Exception) {
				missing = true;
			}
			if (missing)
				ThrowParseException (
					"Error parsing attribute '{0}': Type '{1}' does not have a public property named '{0}'",
					memberName, inherits);
			
			Type memberType = null;
			if (mi is PropertyInfo) {
				PropertyInfo pi = mi as PropertyInfo;
				
				if (!pi.CanWrite)
					ThrowParseException (
						"Error parsing attribute '{0}': The '{0}' property is read-only and cannot be set.",
						memberName);
				memberType = pi.PropertyType;
			} else if (mi is FieldInfo) {
				memberType = ((FieldInfo)mi).FieldType;
			} else
				ThrowParseException ("Could not determine member the kind of '{0}' in base type '{1}",
						     memberName, inherits);
			TypeConverter converter = TypeDescriptor.GetConverter (memberType);
			bool convertible = true;
			object value = null;
			
			if (converter == null || !converter.CanConvertFrom (typeof (string)))
				convertible = false;

			if (convertible) {
				try {
					value = converter.ConvertFromInvariantString (val);
				} catch (Exception) {
					convertible = false;
				}
			}

			if (!convertible)
				ThrowParseException ("Error parsing attribute '{0}': Cannot create an object of type '{1}' from its string representation '{2}' for the '{3}' property.",
						     memberName, memberType, val, mi.Name);
			
			UnknownAttributeDescriptor desc = new UnknownAttributeDescriptor (mi, value);
			unknownMainAttributes.Add (desc);
		}
		
		internal void SetBaseType (string type)
		{
			Type parent;			
			if (type == null || type == DefaultBaseTypeName)
				parent = DefaultBaseType;
			else
				parent = null;

			if (parent == null) {
				parent = LoadType (type);

				if (parent == null)
					ThrowParseException ("Cannot find type " + type);

				if (!DefaultBaseType.IsAssignableFrom (parent))
					ThrowParseException ("The parent type '" + type + "' does not derive from " + DefaultBaseType);
			}

			var pageParserFilter = PageParserFilter;
			if (pageParserFilter != null && !pageParserFilter.AllowBaseType (parent))
				throw new HttpException ("Base type '" + parent + "' is not allowed.");
			
			baseType = parent;
		}

		internal void SetLanguage (string language)
		{
			this.language = language;
			implicitLanguage = false;
		}

		internal void PushIncludeDir (string dir)
		{
			if (includeDirs == null)
				includeDirs = new Stack <string> (1);

			includeDirs.Push (dir);
		}

		internal string PopIncludeDir ()
		{
			if (includeDirs == null || includeDirs.Count == 0)
				return null;

			return includeDirs.Pop () as string;
		}
		
		Assembly GetAssemblyFromSource (string vpath)
		{			
			vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
			string realPath = MapPath (vpath, false);
			if (!File.Exists (realPath))
				ThrowParseException ("File " + vpath + " not found");

			AddSourceDependency (vpath);
			
			CompilerResults result;
			string tmp;
			CompilerParameters parameters;
			CodeDomProvider provider = BaseCompiler.CreateProvider (HttpContext.Current, language, out parameters, out tmp);
			if (provider == null)
				throw new HttpException ("Cannot find provider for language '" + language + "'.");
			
			AssemblyBuilder abuilder = new AssemblyBuilder (provider);
			abuilder.CompilerOptions = parameters;
			abuilder.AddAssemblyReference (BuildManager.GetReferencedAssemblies () as List <Assembly>);
			abuilder.AddCodeFile (realPath);
			result = abuilder.BuildAssembly (new VirtualPath (vpath));

			if (result.NativeCompilerReturnValue != 0) {
				using (StreamReader reader = new StreamReader (realPath)) {
					throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
				}
			}

			AddAssembly (result.CompiledAssembly, true);
			return result.CompiledAssembly;
		}		

		internal abstract string DefaultBaseTypeName { get; }
		internal abstract string DefaultDirectiveName { get; }

		internal bool LinePragmasOn {
			get { return linePragmasOn; }
		}
		
		internal byte[] MD5Checksum {
			get { return md5checksum; }
			set { md5checksum = value; }
		}

		internal PageParserFilter PageParserFilter {
			get {
				if (pageParserFilter != null)
					return pageParserFilter;

				Type t = PageParserFilterType;
				if (t == null)
					return null;
				
				pageParserFilter = Activator.CreateInstance (t) as PageParserFilter;
				pageParserFilter.Initialize (this);

				return pageParserFilter;
			}
		}
		
		internal Type PageParserFilterType {
			get {
				if (pageParserFilterType == null) {
					pageParserFilterType = PageParser.DefaultPageParserFilterType;
					if (pageParserFilterType != null)
						return pageParserFilterType;
					string typeName = PagesConfig.PageParserFilterType;
					if (String.IsNullOrEmpty (typeName))
						return null;
					
					pageParserFilterType = HttpApplication.LoadType (typeName, true);
				}
				
				return pageParserFilterType;
			}
		}
		internal virtual
		Type DefaultBaseType {
			get {
				Type type = Type.GetType (DefaultBaseTypeName, true);

				return type;
			}
		}
		
		internal ILocation DirectiveLocation {
			get { return directiveLocation; }
		}
		
		internal string ParserDir {
			get {
				if (includeDirs == null || includeDirs.Count == 0)
					return BaseDir;

				return includeDirs.Peek () as string;
			}
		}
		
		internal string InputFile
		{
			get { return inputFile; }
			set { inputFile = value; }
		}

		internal bool IsPartial {
			get { return (!srcIsLegacy && src != null); }
		}

		internal string CodeBehindSource {
			get {
				if (srcIsLegacy)
					return null;
				
				return src;
			}
		}
			
		internal string PartialClassName {
			get { return partialClassName; }
		}

		internal string CodeFileBaseClass {
			get { return codeFileBaseClass; }
		}

		internal string MetaResourceKey {
			get { return metaResourceKey; }
		}
		
		internal Type CodeFileBaseClassType
		{
			get { return codeFileBaseClassType; }
		}
		
		internal List <UnknownAttributeDescriptor> UnknownMainAttributes
		{
			get { return unknownMainAttributes; }
		}

		internal string Text {
			get { return text; }
			set { text = value; }
		}

		internal Type BaseType {
			get {
				if (baseType == null)
					SetBaseType (DefaultBaseTypeName);
				
				return baseType;
			}
		}
		
		internal bool BaseTypeIsGlobal {
			get { return baseTypeIsGlobal; }
			set { baseTypeIsGlobal = value; }
		}

		static long autoClassCounter = 0;

		internal string EncodeIdentifier (string value)
		{
			if (value == null || value.Length == 0 || CodeGenerator.IsValidLanguageIndependentIdentifier (value))
				return value;

			StringBuilder ret = new StringBuilder ();

			char ch = value [0];
			switch (Char.GetUnicodeCategory (ch)) {
				case UnicodeCategory.LetterNumber:
				case UnicodeCategory.LowercaseLetter:
				case UnicodeCategory.TitlecaseLetter:
				case UnicodeCategory.UppercaseLetter:
				case UnicodeCategory.OtherLetter:
				case UnicodeCategory.ModifierLetter:
				case UnicodeCategory.ConnectorPunctuation:
					ret.Append (ch);
					break;

				case UnicodeCategory.DecimalDigitNumber:
					ret.Append ('_');
					ret.Append (ch);
					break;
					
				default:
					ret.Append ('_');
					break;
			}

			for (int i = 1; i < value.Length; i++) {
				ch = value [i];
				switch (Char.GetUnicodeCategory (ch)) {
					case UnicodeCategory.LetterNumber:
					case UnicodeCategory.LowercaseLetter:
					case UnicodeCategory.TitlecaseLetter:
					case UnicodeCategory.UppercaseLetter:
					case UnicodeCategory.OtherLetter:
					case UnicodeCategory.ModifierLetter:
					case UnicodeCategory.ConnectorPunctuation:
					case UnicodeCategory.DecimalDigitNumber:
					case UnicodeCategory.NonSpacingMark:
					case UnicodeCategory.SpacingCombiningMark:
					case UnicodeCategory.Format:
						ret.Append (ch);
						break;
						
					default:
						ret.Append ('_');
						break;
				}
			}

			return ret.ToString ();
		}
		
		internal string ClassName {
			get {
				if (className != null)
					return className;

				string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
				string inFile;
				
				if (String.IsNullOrEmpty (inputFile)) {
					inFile = null;
					using (StreamReader sr = Reader as StreamReader) {
						if (sr != null) {
							FileStream fr = sr.BaseStream as FileStream;
							if (fr != null)
								inFile = fr.Name;
						}
					}
				} else
					inFile = inputFile;

				if (String.IsNullOrEmpty (inFile)) {
					// generate a unique class name
					long suffix;
					suffix = Interlocked.Increment (ref autoClassCounter);
					className = String.Format ("autoclass_nosource_{0:x}", suffix);
					return className;
				}
				
				if (StrUtils.StartsWith (inFile, physPath))
					className = inputFile.Substring (physPath.Length).ToLower (Helpers.InvariantCulture);
				else
					className = Path.GetFileName (inputFile);
				className = EncodeIdentifier (className);
				return className;
			}
		}

		internal List <ServerSideScript> Scripts {
			get {
				if (scripts == null)
					scripts = new List <ServerSideScript> ();

				return scripts;
			}
		}

		internal Dictionary <string, bool> Imports {
			get { return imports; }
		}

		internal List <string> Interfaces {
			get { return interfaces; }
		}
		
		internal List <string> Assemblies {
			get {
				if (appAssemblyIndex != -1) {
					string o = assemblies [appAssemblyIndex];
					assemblies.RemoveAt (appAssemblyIndex);
					assemblies.Add (o);
					appAssemblyIndex = -1;
				}

				return assemblies;
			}
		}

		internal RootBuilder RootBuilder {
			get {
				if (rootBuilder != null)
					return rootBuilder;
				AspGenerator generator = AspGenerator;
				if (generator != null)
					rootBuilder = generator.RootBuilder;

				return rootBuilder;
			}
			set { rootBuilder = value; }
		}

		internal List <string> Dependencies {
			get { return dependencies; }
			set { dependencies = value; }
		}

		internal string CompilerOptions {
			get { return compilerOptions; }
		}

		internal string Language {
			get { return language; }
		}

		internal bool ImplicitLanguage {
			get { return implicitLanguage; }
		}
		
		internal bool StrictOn {
			get { return strictOn; }
		}

		internal bool ExplicitOn {
			get { return explicitOn; }
		}
		
		internal bool Debug {
			get { return debug; }
		}

		internal bool OutputCache {
			get { return output_cache; }
		}

		internal int OutputCacheDuration {
			get { return oc_duration; }
		}

		internal OutputCacheParsedParams OutputCacheParsedParameters {
			get { return oc_parsed_params; }
		}

		internal string OutputCacheSqlDependency {
			get { return oc_sqldependency; }
		}
		
		internal string OutputCacheCacheProfile {
			get { return oc_cacheprofile; }
		}
		
		internal string OutputCacheVaryByContentEncodings {
			get { return oc_content_encodings; }
		}

		internal bool OutputCacheNoStore {
			get { return oc_nostore; }
		}
		
		internal virtual TextReader Reader {
			get { return null; }
			set { /* no-op */ }
		}
		
		internal string OutputCacheVaryByHeader {
			get { return oc_header; }
		}

		internal string OutputCacheVaryByCustom {
			get { return oc_custom; }
		}

		internal string OutputCacheVaryByControls {
			get { return oc_controls; }
		}
		
		internal bool OutputCacheShared {
			get { return oc_shared; }
		}
		
		internal OutputCacheLocation OutputCacheLocation {
			get { return oc_location; }
		}

		internal string OutputCacheVaryByParam {
			get { return oc_param; }
		}

		internal List <string> RegisteredTagNames {
			get { return registeredTagNames; }
		}
		
		internal PagesSection PagesConfig {
			get { return GetConfigSection <PagesSection> ("system.web/pages") as PagesSection; }
		}

		internal AspGenerator AspGenerator {
			get;
			set;
		}
	}
}