2 // System.Web.Compilation.AspGenerator
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 // Copyright (c) 2004,2006 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.CodeDom.Compiler;
34 using System.Globalization;
37 using System.Text.RegularExpressions;
38 using System.Web.Caching;
39 using System.Web.Configuration;
40 using System.Web.Hosting;
42 using System.Web.UI.HtmlControls;
43 using System.Web.Util;
46 using System.Collections.Generic;
49 namespace System.Web.Compilation
53 public ControlBuilder Builder;
54 public ILocation Location;
56 public BuilderLocation (ControlBuilder builder, ILocation location)
58 this.Builder = builder;
59 this.Location = location;
63 class BuilderLocationStack : Stack
65 public override void Push (object o)
67 if (!(o is BuilderLocation))
68 throw new InvalidOperationException ();
73 public virtual void Push (ControlBuilder builder, ILocation location)
75 BuilderLocation bl = new BuilderLocation (builder, location);
79 public new BuilderLocation Peek ()
81 return (BuilderLocation) base.Peek ();
84 public new BuilderLocation Pop ()
86 return (BuilderLocation) base.Pop ();
89 public ControlBuilder Builder {
90 get { return Peek ().Builder; }
100 public ParserStack ()
102 files = new Hashtable (); // may be this should be case sensitive for windows
103 parsers = new Stack ();
106 public bool Push (AspParser parser)
108 if (files.Contains (parser.Filename))
111 files [parser.Filename] = true;
112 parsers.Push (parser);
117 public AspParser Pop ()
119 if (parsers.Count == 0)
122 files.Remove (current.Filename);
123 AspParser result = (AspParser) parsers.Pop ();
124 if (parsers.Count > 0)
125 current = (AspParser) parsers.Peek ();
133 get { return parsers.Count; }
136 public AspParser Parser {
137 get { return current; }
140 public string Filename {
141 get { return current.Filename; }
154 public void Push (string tagid)
164 return (string) tags.Pop ();
167 public bool CompareTo (string tagid)
172 return 0 == String.Compare (tagid, (string) tags.Peek (), true, CultureInfo.InvariantCulture);
176 get { return tags.Count; }
179 public string Current {
180 get { return (string) tags.Peek (); }
187 const int READ_BUFFER_SIZE = 8192;
189 internal static Regex DirectiveRegex = new Regex (@"<%\s*@(\s*(?<attrname>\w[\w:]*(?=\W))(\s*(?<equal>=)\s*""(?<attrval>[^""]*)""|\s*(?<equal>=)\s*'(?<attrval>[^']*)'|\s*(?<equal>=)\s*(?<attrval>[^\s%>]*)|(?<equal>)(?<attrval>\s*?)))*\s*?%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
192 BuilderLocationStack stack;
193 TemplateParser tparser;
195 RootBuilder rootBuilder;
196 bool inScript, javascript, ignore_text;
199 StringBuilder tagInnerText = new StringBuilder ();
200 static Hashtable emptyHash = new Hashtable ();
205 AspComponentFoundry componentFoundry;
208 public AspGenerator (TemplateParser tparser, AspComponentFoundry componentFoundry) : this (tparser)
210 this.componentFoundry = componentFoundry;
214 public AspGenerator (TemplateParser tparser)
216 this.tparser = tparser;
217 text = new StringBuilder ();
218 stack = new BuilderLocationStack ();
221 rootBuilder = new RootBuilder (tparser);
222 tparser.RootBuilder = rootBuilder;
223 stack.Push (rootBuilder, null);
225 pstack = new ParserStack ();
228 public RootBuilder RootBuilder {
229 get { return rootBuilder; }
232 public AspParser Parser {
233 get { return pstack.Parser; }
236 public string Filename {
237 get { return pstack.Filename; }
241 PageParserFilter PageParserFilter {
246 return tparser.PageParserFilter;
252 // The kludge to determine the base type of the to-be-generated ASP.NET class is
253 // very unfortunate but with our current parser it is, unfortunately, necessary. The
254 // reason for reading the entire file into memory and parsing it with a regexp is
255 // that we need to read the main directive (i.e. <%@Page %>, <%@Control %> etc),
256 // pass it to the page parser filter if it exists, and finally read the inherits
257 // attribute of the directive to get access to the base type of the class to be
258 // generated. On that type we check whether it is decorated with the
259 // FileLevelControlBuilder attribute and, if yes, use the indicated type as the
260 // RootBuilder. This is necessary for the ASP.NET MVC views using the "generic"
261 // inherits declaration to work properly. Our current parser is not able to parse
262 // the input file out of sequence (i.e. directives first, then the rest) so we need
263 // to do what we do below, alas.
264 Hashtable GetDirectiveAttributesDictionary (string skipKeyName, CaptureCollection names, CaptureCollection values)
266 var ret = new Hashtable (StringComparer.InvariantCultureIgnoreCase);
270 foreach (Capture c in names) {
272 if (String.Compare (skipKeyName, keyName, StringComparison.OrdinalIgnoreCase) == 0) {
277 ret.Add (c.Value, values [index++].Value);
283 string GetDirectiveName (CaptureCollection names)
286 foreach (Capture c in names) {
288 if (Directive.IsDirective (val))
292 return tparser.DefaultDirectiveName;
295 int GetLineNumberForIndex (string fileContents, int index)
299 bool foundCR = false;
301 for (int pos = 0; pos < index; pos++) {
302 c = fileContents [pos];
303 if (c == '\n' || foundCR) {
308 foundCR = (c == '\r');
314 int GetNumberOfLinesForRange (string fileContents, int index, int length)
317 int stop = index + length;
319 bool foundCR = false;
321 for (int pos = index; pos < stop; pos++) {
322 c = fileContents [pos];
323 if (c == '\n' || foundCR) {
328 foundCR = (c == '\r');
334 Type GetInheritedType (string fileContents, string filename)
336 MatchCollection matches = DirectiveRegex.Matches (fileContents);
337 if (matches == null || matches.Count == 0)
340 string wantedDirectiveName = tparser.DefaultDirectiveName.ToLower ();
341 string directiveName;
342 GroupCollection groups;
343 CaptureCollection ccNames;
345 foreach (Match match in matches) {
346 groups = match.Groups;
347 if (groups.Count < 6)
350 ccNames = groups [3].Captures;
351 directiveName = GetDirectiveName (ccNames);
352 if (String.IsNullOrEmpty (directiveName))
355 if (String.Compare (directiveName.ToLower (), wantedDirectiveName, StringComparison.Ordinal) != 0)
358 var loc = new Location (null);
359 int index = match.Index;
361 loc.Filename = filename;
362 loc.BeginLine = GetLineNumberForIndex (fileContents, index);
363 loc.EndLine = loc.BeginLine + GetNumberOfLinesForRange (fileContents, index, match.Length);
365 tparser.Location = loc;
366 tparser.allowedMainDirectives = 2;
367 tparser.AddDirective (wantedDirectiveName, GetDirectiveAttributesDictionary (wantedDirectiveName, ccNames, groups [5].Captures));
369 return tparser.BaseType;
375 string ReadFileContents (Stream inputStream, string filename)
379 if (inputStream != null) {
380 if (inputStream.CanSeek) {
381 long curPos = inputStream.Position;
382 inputStream.Seek (0, SeekOrigin.Begin);
384 Encoding enc = WebEncoding.FileEncoding;
385 StringBuilder sb = new StringBuilder ();
386 byte[] buffer = new byte [READ_BUFFER_SIZE];
389 while ((nbytes = inputStream.Read (buffer, 0, READ_BUFFER_SIZE)) > 0)
390 sb.Append (enc.GetString (buffer, 0, nbytes));
391 inputStream.Seek (curPos, SeekOrigin.Begin);
393 ret = sb.ToString ();
397 FileStream fs = inputStream as FileStream;
399 string fname = fs.Name;
401 if (File.Exists (fname))
402 ret = File.ReadAllText (fname);
410 if (ret == null && !String.IsNullOrEmpty (filename) && String.Compare (filename, "@@inner_string@@", StringComparison.Ordinal) != 0) {
412 if (File.Exists (filename))
413 ret = File.ReadAllText (filename);
422 Type GetRootBuilderType (Stream inputStream, string filename)
428 fileContents = ReadFileContents (inputStream, filename);
432 if (!String.IsNullOrEmpty (fileContents)) {
433 Type inheritedType = GetInheritedType (fileContents, filename);
435 if (inheritedType != null) {
436 FileLevelControlBuilderAttribute attr;
439 object[] attrs = inheritedType.GetCustomAttributes (typeof (FileLevelControlBuilderAttribute), true);
440 if (attrs != null && attrs.Length > 0)
441 attr = attrs [0] as FileLevelControlBuilderAttribute;
448 ret = attr != null ? attr.BuilderType : null;
453 if (tparser is PageParser)
454 return typeof (FileLevelPageControlBuilder);
455 else if (tparser is UserControlParser)
456 return typeof (FileLevelUserControlBuilder);
458 return typeof (RootBuilder);
463 void CreateRootBuilder (Stream inputStream, string filename)
465 if (rootBuilder != null)
468 Type rootBuilderType = GetRootBuilderType (inputStream, filename);
469 rootBuilder = Activator.CreateInstance (rootBuilderType) as RootBuilder;
470 if (rootBuilder == null)
471 throw new HttpException ("Cannot create an instance of file-level control builder.");
472 rootBuilder.Init (tparser, null, null, null, null, null);
473 if (componentFoundry != null)
474 rootBuilder.Foundry = componentFoundry;
476 stack.Push (rootBuilder, null);
477 tparser.RootBuilder = rootBuilder;
481 BaseCompiler GetCompilerFromType ()
483 Type type = tparser.GetType ();
484 if (type == typeof (PageParser))
485 return new PageCompiler ((PageParser) tparser);
487 if (type == typeof (ApplicationFileParser))
488 return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
490 if (type == typeof (UserControlParser))
491 return new UserControlCompiler ((UserControlParser) tparser);
493 if (type == typeof(MasterPageParser))
494 return new MasterPageCompiler ((MasterPageParser) tparser);
497 throw new Exception ("Got type: " + type);
500 void InitParser (TextReader reader, string filename)
502 AspParser parser = new AspParser (filename, reader);
503 parser.Error += new ParseErrorHandler (ParseError);
504 parser.TagParsed += new TagParsedHandler (TagParsed);
505 parser.TextParsed += new TextParsedHandler (TextParsed);
507 parser.ParsingComplete += new ParsingCompleteHandler (ParsingCompleted);
508 tparser.AspGenerator = this;
509 CreateRootBuilder (inputStream, filename);
511 if (!pstack.Push (parser))
512 throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
514 if (filename != "@@inner_string@@") {
515 string arvp = Path.Combine (tparser.BaseVirtualDir, Path.GetFileName (filename));
516 if (VirtualPathUtility.IsAbsolute (arvp))
517 arvp = VirtualPathUtility.ToAppRelative (arvp);
519 tparser.AddDependency (arvp);
524 void InitParser (string filename)
526 StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
527 InitParser (reader, filename);
531 public void Parse (string file)
540 public void Parse (TextReader reader, string filename, bool doInitParser)
543 isApplication = tparser.DefaultDirectiveName == "application";
546 InitParser (reader, filename);
548 pstack.Parser.Parse ();
553 tparser.MD5Checksum = pstack.Parser.MD5Checksum;
558 PrintTree (RootBuilder, 0);
561 if (stack.Count > 1 && pstack.Count == 0)
562 throw new ParseException (stack.Builder.Location,
563 "Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
571 public void Parse (Stream stream, string filename, bool doInitParser)
574 inputStream = stream;
576 Parse (new StreamReader (stream, WebEncoding.FileEncoding), filename, doInitParser);
579 public void Parse (string filename, bool doInitParser)
581 StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
582 Parse (reader, filename, doInitParser);
588 string inputFile = tparser.InputFile;
589 TextReader inputReader = tparser.Reader;
592 if (String.IsNullOrEmpty (inputFile)) {
593 StreamReader sr = inputReader as StreamReader;
595 FileStream fr = sr.BaseStream as FileStream;
600 if (String.IsNullOrEmpty (inputFile))
601 inputFile = "@@inner_string@@";
604 if (inputReader != null) {
605 Parse (inputReader, inputFile, true);
607 if (String.IsNullOrEmpty (inputFile))
608 throw new HttpException ("Parser input file is empty, cannot continue.");
609 inputFile = Path.GetFullPath (inputFile);
610 InitParser (inputFile);
614 if (inputReader != null)
615 inputReader.Close ();
618 Parse (Path.GetFullPath (tparser.InputFile));
622 internal static void AddTypeToCache (ArrayList dependencies, string inputFile, Type type)
624 if (type == null || inputFile == null || inputFile.Length == 0)
627 if (dependencies != null && dependencies.Count > 0) {
628 string [] deps = (string []) dependencies.ToArray (typeof (string));
629 HttpContext ctx = HttpContext.Current;
630 HttpRequest req = ctx != null ? ctx.Request : null;
633 throw new HttpException ("No current context, cannot compile.");
635 for (int i = 0; i < deps.Length; i++)
636 deps [i] = req.MapPath (deps [i]);
638 HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type, new CacheDependency (deps));
640 HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type);
643 public Type GetCompiledType ()
645 Type type = (Type) HttpRuntime.InternalCache.Get ("@@Type" + tparser.InputFile);
652 BaseCompiler compiler = GetCompilerFromType ();
654 type = compiler.GetCompiledType ();
655 AddTypeToCache (tparser.Dependencies, tparser.InputFile, type);
660 static void PrintTree (ControlBuilder builder, int indent)
665 string i = new string ('\t', indent);
667 Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
668 builder, builder.ID, builder.ControlType, builder.ParentBuilder);
670 if (builder.Children != null)
671 foreach (object o in builder.Children) {
672 if (o is ControlBuilder)
673 PrintTree ((ControlBuilder) o, indent++);
677 static void PrintLocation (ILocation loc)
679 Console.WriteLine ("\tFile name: " + loc.Filename);
680 Console.WriteLine ("\tBegin line: " + loc.BeginLine);
681 Console.WriteLine ("\tEnd line: " + loc.EndLine);
682 Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
683 Console.WriteLine ("\tEnd column: " + loc.EndColumn);
684 Console.WriteLine ("\tPlainText: " + loc.PlainText);
685 Console.WriteLine ();
689 void ParseError (ILocation location, string message)
691 throw new ParseException (location, message);
696 // The code below (ProcessTagsInAttributes, ParseAttributeTag) serves the purpose to work
697 // around a limitation of the current asp.net parser which is unable to parse server
698 // controls inside client tag attributes. Since the architecture of the current
699 // parser does not allow for clean solution of this problem, hence the kludge
700 // below. It will be gone as soon as the parser is rewritten.
702 // The kludge supports only self-closing tags inside attributes.
705 static readonly Regex runatServer=new Regex (@"<[\w:\.]+.*?runat=[""']?server[""']?.*?/>",
706 RegexOptions.Compiled | RegexOptions.Singleline |
707 RegexOptions.Multiline | RegexOptions.IgnoreCase |
708 RegexOptions.CultureInvariant);
709 bool ProcessTagsInAttributes (ILocation location, string tagid, TagAttributes attributes, TagType type)
711 if (attributes == null || attributes.Count == 0)
719 StringBuilder sb = new StringBuilder ();
721 sb.AppendFormat ("\t<{0}", tagid);
722 foreach (string key in attributes.Keys) {
723 value = attributes [key] as string;
724 if (value == null || value.Length < 16) { // optimization
725 sb.AppendFormat (" {0}=\"{1}\"", key, value);
729 match = runatServer.Match (attributes [key] as string);
730 if (!match.Success) {
731 sb.AppendFormat (" {0}=\"{1}\"", key, value);
735 TextParsed (location, sb.ToString ());
740 group = match.Groups [0];
742 length = group.Length;
744 TextParsed (location, String.Format (" {0}=\"{1}", key, index > 0 ? value.Substring (0, index) : String.Empty));;
746 ParseAttributeTag (group.Value);
747 if (index + length < value.Length)
748 TextParsed (location, value.Substring (index + length) + "\"");
750 TextParsed (location, "\"");
752 if (type == TagType.SelfClosing)
757 if (retval && sb.Length > 0)
758 TextParsed (location, sb.ToString ());
763 void ParseAttributeTag (string code)
765 AspParser parser = new AspParser ("@@attribute_tag@@", new StringReader (code));
766 parser.Error += new ParseErrorHandler (ParseError);
767 parser.TagParsed += new TagParsedHandler (TagParsed);
768 parser.TextParsed += new TextParsedHandler (TextParsed);
775 void ParsingCompleted ()
777 PageParserFilter pfilter = PageParserFilter;
781 pfilter.ParseComplete (RootBuilder);
785 void CheckIfIncludeFileIsSecure (string filePath)
787 if (filePath == null || filePath.Length == 0)
790 // a bit slow, but fully portable
791 string newdir = null;
792 Exception exception = null;
794 string origdir = Directory.GetCurrentDirectory ();
795 Directory.SetCurrentDirectory (Path.GetDirectoryName (filePath));
796 newdir = Directory.GetCurrentDirectory ();
797 Directory.SetCurrentDirectory (origdir);
798 if (newdir [newdir.Length - 1] != '/')
800 } catch (DirectoryNotFoundException) {
801 return; // will be converted into 404
802 } catch (FileNotFoundException) {
804 } catch (Exception ex) {
805 // better safe than sorry
809 if (exception != null || !StrUtils.StartsWith (newdir, HttpRuntime.AppDomainAppPath))
810 throw new ParseException (Location, "Files above the application's root directory cannot be included.");
813 void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
817 this.location = new Location (location);
819 tparser.Location = location;
821 if (text.Length != 0)
822 FlushText (lastTag == TagType.CodeRender);
824 if (0 == String.Compare (tagid, "script", true, CultureInfo.InvariantCulture)) {
825 bool in_script = (inScript || ignore_text);
827 if (ProcessScript (tagtype, attributes))
830 if (ProcessScript (tagtype, attributes))
836 case TagType.Directive:
837 if (tagid.Length == 0)
838 tagid = tparser.DefaultDirectiveName;
840 tparser.AddDirective (tagid, attributes.GetDictionary (null));
843 if (ProcessTag (location, tagid, attributes, tagtype, out tagIgnored)) {
850 stack.Builder.EnsureOtherTags ();
851 stack.Builder.OtherTags.Add (tagid);
855 string plainText = location.PlainText;
856 if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.Tag))
857 TextParsed (location, plainText);
861 bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
862 if (!notServer && CloseControl (tagid))
865 TextParsed (location, location.PlainText);
867 case TagType.SelfClosing:
868 int count = stack.Count;
869 if (!ProcessTag (location, tagid, attributes, tagtype, out tagIgnored) && !tagIgnored) {
870 string plainText = location.PlainText;
871 if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.SelfClosing))
872 TextParsed (location, plainText);
873 } else if (stack.Count != count) {
874 CloseControl (tagid);
877 case TagType.DataBinding:
878 goto case TagType.CodeRender;
879 case TagType.CodeRenderExpression:
880 goto case TagType.CodeRender;
881 case TagType.CodeRender:
883 throw new ParseException (location, "Invalid content for application file.");
885 ProcessCode (tagtype, tagid, location);
887 case TagType.Include:
889 throw new ParseException (location, "Invalid content for application file.");
891 string file = attributes ["virtual"] as string;
892 bool isvirtual = (file != null);
894 file = attributes ["file"] as string;
899 VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
901 if (vpp.FileExists (file)) {
902 VirtualFile vf = vpp.GetFile (file);
904 Parse (vf.Open (), file, true);
911 Parse (tparser.MapPath (file), true);
913 string includeFilePath = GetIncludeFilePath (tparser.ParserDir, file);
914 CheckIfIncludeFileIsSecure (includeFilePath);
915 tparser.PushIncludeDir (Path.GetDirectoryName (includeFilePath));
917 Parse (includeFilePath, true);
919 tparser.PopIncludeDir ();
927 //PrintLocation (location);
930 static bool TryRemoveTag (string tagid, ArrayList otags)
932 if (otags == null || otags.Count == 0)
935 for (int idx = otags.Count - 1; idx >= 0; idx--) {
936 string otagid = (string) otags [idx];
937 if (0 == String.Compare (tagid, otagid, true, CultureInfo.InvariantCulture)) {
939 otags.RemoveAt (idx);
940 } while (otags.Count - 1 >= idx);
947 static string GetIncludeFilePath (string basedir, string filename)
949 if (Path.DirectorySeparatorChar == '/')
950 filename = filename.Replace ("\\", "/");
952 return Path.GetFullPath (Path.Combine (basedir, filename));
955 void TextParsed (ILocation location, string text)
960 // Another gross hack - get rid of comments in the parsed text
961 int textLen = text.Length;
962 int textMaxIndex = textLen - 1;
963 int commentStart = text.IndexOf ("<!--");
964 int commentLastStart = 0;
966 List <int> commentRanges = null;
968 ArrayList commentRanges = null;
971 while (commentStart != -1) {
972 int commentEnd = text.IndexOf ("-->", commentStart);
974 if (commentEnd == -1) {
975 if (commentStart == 0)
977 commentEnd = textMaxIndex;
980 if (commentRanges == null) {
982 commentRanges = new List <int> ();
984 commentRanges = new ArrayList ();
988 if (commentStart > commentLastStart) {
989 commentRanges.Add (commentLastStart);
990 commentRanges.Add (commentStart);
993 if (commentEnd == textMaxIndex)
996 commentLastStart = commentEnd + 3;
997 if (commentLastStart > textMaxIndex)
1000 commentStart = text.IndexOf ("<!--", commentLastStart);
1001 if (commentStart == -1) {
1002 int tailLength = textMaxIndex - commentLastStart;
1003 if (tailLength > 0) {
1004 commentRanges.Add (commentLastStart);
1005 commentRanges.Add (tailLength);
1011 if (commentRanges != null) {
1012 if (commentRanges.Count == 0)
1015 StringBuilder sb = new StringBuilder ();
1016 for (int i = 0; i < commentRanges.Count; i += 2) {
1018 sb.Append (text.Substring (commentRanges [i], commentRanges [i + 1]));
1020 sb.Append (text.Substring ((int)commentRanges [i], (int)commentRanges [i + 1]));
1024 string noComments = sb.ToString ().Trim ();
1025 if (noComments.Length == 0)
1031 // And again... the first one wins - if we have expressions and server-side
1032 // controls together in one block of plain text, tough luck...
1033 if (text.IndexOf ("<%") != -1 && !inScript) {
1034 if (this.text.Length > 0)
1036 CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
1037 r.AddChildren (this);
1041 int startIndex = 0, index = 0;
1044 while (index > -1 && startIndex < textLen) {
1045 match = runatServer.Match (text, index);
1047 if (match.Success) {
1048 string value = match.Value;
1049 index = match.Index;
1050 if (index > startIndex)
1051 this.text.Append (text.Substring (startIndex, index - startIndex));
1052 ParseAttributeTag (value);
1053 index += value.Length;
1058 if (index < textLen)
1059 index = text.IndexOf ('<', index);
1064 this.text.Append (text.Substring (startIndex));
1065 //PrintLocation (location);
1073 void FlushText (bool ignoreEmptyString)
1075 string t = text.ToString ();
1078 if (ignoreEmptyString && t.Trim ().Length == 0)
1083 PageParserFilter pfilter = PageParserFilter;
1084 if (pfilter != null && !pfilter.ProcessCodeConstruct (CodeConstructType.ScriptTag, t))
1087 tparser.Scripts.Add (new ServerSideScript (t, new System.Web.Compilation.Location (tparser.Location)));
1091 if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
1092 throw new ParseException (location, "Content not valid for application file.");
1094 ControlBuilder current = stack.Builder;
1095 current.AppendLiteralString (t);
1096 if (current.NeedsTagInnerText ()) {
1097 tagInnerText.Append (t);
1102 bool BuilderHasOtherThan (Type type, ControlBuilder cb)
1104 ArrayList al = cb.OtherTags;
1105 if (al != null && al.Count > 0)
1112 foreach (object o in al) {
1116 tmp = o as ControlBuilder;
1118 string s = o as string;
1119 if (s != null && String.IsNullOrEmpty (s.Trim ()))
1125 if (tmp is System.Web.UI.WebControls.ContentBuilderInternal)
1128 if (tmp.ControlType != typeof (System.Web.UI.WebControls.Content))
1136 bool OtherControlsAllowed (ControlBuilder cb)
1141 if (!typeof (System.Web.UI.WebControls.Content).IsAssignableFrom (cb.ControlType))
1144 if (BuilderHasOtherThan (typeof (System.Web.UI.WebControls.Content), RootBuilder))
1151 public void AddControl (Type type, IDictionary attributes)
1153 ControlBuilder parent = stack.Builder;
1154 ControlBuilder builder = ControlBuilder.CreateBuilderFromType (tparser, parent, type, null, null,
1155 attributes, location.BeginLine,
1157 if (builder != null)
1158 parent.AppendSubBuilder (builder);
1161 bool ProcessTag (ILocation location, string tagid, TagAttributes atts, TagType tagtype, out bool ignored)
1164 if (isApplication) {
1165 if (String.Compare (tagid, "object", true, CultureInfo.InvariantCulture) != 0)
1166 throw new ParseException (location, "Invalid tag for application file.");
1169 ControlBuilder parent = stack.Builder;
1170 ControlBuilder builder = null;
1171 if (parent != null && parent.ControlType == typeof (HtmlTable) &&
1172 (String.Compare (tagid, "thead", true, CultureInfo.InvariantCulture) == 0 ||
1173 String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0)) {
1178 Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
1179 if (stack.Count > 1) {
1181 builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
1182 } catch (TypeLoadException e) {
1183 throw new ParseException (Location, "Type not found.", e);
1184 } catch (Exception e) {
1185 throw new ParseException (Location, e.Message, e);
1189 bool runatServer = atts != null && atts.IsRunAtServer ();
1190 if (builder == null && runatServer) {
1191 string id = htable ["id"] as string;
1192 if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
1193 throw new ParseException (Location, "'" + id + "' is not a valid identifier");
1196 builder = RootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
1197 } catch (TypeLoadException e) {
1198 throw new ParseException (Location, "Type not found.", e);
1199 } catch (HttpException e) {
1200 CompilationException inner = e.InnerException as CompilationException;
1204 throw new ParseException (Location, e.Message, e);
1205 } catch (Exception e) {
1206 throw new ParseException (Location, e.Message, e);
1210 if (builder == null)
1213 // This is as good as we can do for now - if the parsed location contains
1214 // both expressions and code render blocks then we're out of luck...
1215 string plainText = location.PlainText;
1216 if (!runatServer && plainText.IndexOf ("<%$") == -1&& plainText.IndexOf ("<%") > -1)
1219 PageParserFilter pfilter = PageParserFilter;
1220 if (pfilter != null && !pfilter.AllowControl (builder.ControlType, builder))
1221 throw new ParseException (Location, "Control type '" + builder.ControlType + "' not allowed.");
1223 if (!OtherControlsAllowed (builder))
1224 throw new ParseException (Location, "Only Content controls are allowed directly in a content page that contains Content controls.");
1227 builder.Location = location;
1228 builder.ID = htable ["id"] as string;
1229 if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
1231 throw new ParseException (location, "Only one <form> allowed.");
1236 if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
1237 if (builder is TemplateBuilder) {
1240 stack.Push (builder, location);
1242 if (!isApplication && builder is ObjectTagBuilder) {
1243 ObjectTagBuilder ot = (ObjectTagBuilder) builder;
1244 if (ot.Scope != null && ot.Scope.Length > 0)
1245 throw new ParseException (location, "Scope not allowed here");
1247 if (tagtype == TagType.Tag) {
1248 stack.Push (builder, location);
1253 parent.AppendSubBuilder (builder);
1254 builder.CloseControl ();
1260 string ReadFile (string filename)
1262 string realpath = tparser.MapPath (filename);
1263 using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
1264 string content = sr.ReadToEnd ();
1269 bool ProcessScript (TagType tagtype, TagAttributes attributes)
1271 if (tagtype != TagType.Close) {
1272 if (attributes != null && attributes.IsRunAtServer ()) {
1273 string language = (string) attributes ["language"];
1274 if (language != null && language.Length > 0 && tparser.ImplicitLanguage)
1275 tparser.SetLanguage (language);
1276 CheckLanguage (language);
1277 string src = (string) attributes ["src"];
1280 throw new ParseException (Parser,
1281 "src cannot be an empty string");
1283 string content = ReadFile (src);
1285 TextParsed (Parser, content);
1288 if (tagtype != TagType.SelfClosing) {
1290 Parser.VerbatimID = "script";
1292 } else if (tagtype == TagType.Tag) {
1293 Parser.VerbatimID = "script";
1299 if (tagtype != TagType.SelfClosing) {
1300 Parser.VerbatimID = "script";
1303 TextParsed (location, location.PlainText);
1312 } else if (!ignore_text) {
1313 result = javascript;
1315 TextParsed (location, location.PlainText);
1317 ignore_text = false;
1324 bool CloseControl (string tagid)
1326 ControlBuilder current = stack.Builder;
1327 string btag = current.OriginalTagName;
1328 if (String.Compare (btag, "tbody", true, CultureInfo.InvariantCulture) != 0 &&
1329 String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0) {
1330 if (!current.ChildrenAsProperties) {
1332 TextParsed (location, location.PlainText);
1339 if (current.ControlType == typeof (HtmlTable) && String.Compare (tagid, "thead", true, CultureInfo.InvariantCulture) == 0)
1342 if (0 != String.Compare (tagid, btag, true, CultureInfo.InvariantCulture))
1345 // if (current is TemplateBuilder)
1346 // pop from the id list
1347 if (current.NeedsTagInnerText ()) {
1349 current.SetTagInnerText (tagInnerText.ToString ());
1350 } catch (Exception e) {
1351 throw new ParseException (current.Location, e.Message, e);
1354 tagInnerText.Length = 0;
1357 if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
1361 current.CloseControl ();
1363 stack.Builder.AppendSubBuilder (current);
1368 CodeConstructType MapTagTypeToConstructType (TagType tagtype)
1371 case TagType.CodeRenderExpression:
1372 return CodeConstructType.ExpressionSnippet;
1374 case TagType.CodeRender:
1375 return CodeConstructType.CodeSnippet;
1377 case TagType.DataBinding:
1378 return CodeConstructType.DataBindingSnippet;
1381 throw new InvalidOperationException ("Unexpected tag type.");
1386 bool ProcessCode (TagType tagtype, string code, ILocation location)
1389 PageParserFilter pfilter = PageParserFilter;
1392 // http://msdn.microsoft.com/en-us/library/system.web.ui.pageparserfilter.processcodeconstruct.aspx
1394 // The above page says if false is returned then we should NOT process the
1395 // code further, wheras in reality it's the other way around. The
1396 // ProcessCodeConstruct return value means whether or not the filter
1397 // _processed_ the code.
1399 if (pfilter != null && (!pfilter.AllowCode || pfilter.ProcessCodeConstruct (MapTagTypeToConstructType (tagtype), code)))
1402 ControlBuilder b = null;
1403 if (tagtype == TagType.CodeRender)
1404 b = new CodeRenderBuilder (code, false, location);
1405 else if (tagtype == TagType.CodeRenderExpression)
1406 b = new CodeRenderBuilder (code, true, location);
1407 else if (tagtype == TagType.DataBinding)
1408 b = new DataBindingBuilder (code, location);
1410 throw new HttpException ("Should never happen");
1412 stack.Builder.AppendSubBuilder (b);
1416 public ILocation Location {
1417 get { return location; }
1420 void CheckLanguage (string lang)
1422 if (lang == null || lang == "")
1425 if (String.Compare (lang, tparser.Language, true, CultureInfo.InvariantCulture) == 0)
1429 CompilationSection section = (CompilationSection) WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
1430 if (section.Compilers[tparser.Language] != section.Compilers[lang])
1432 CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
1433 if (!cfg.Compilers.CompareLanguages (tparser.Language, lang))
1435 throw new ParseException (Location,
1436 String.Format ("Trying to mix language '{0}' and '{1}'.",
1437 tparser.Language, lang));
1440 // Used to get CodeRender tags in attribute values
1441 class CodeRenderParser
1444 ControlBuilder builder;
1445 AspGenerator generator;
1447 public CodeRenderParser (string str, ControlBuilder builder)
1450 this.builder = builder;
1453 public void AddChildren (AspGenerator generator)
1455 this.generator = generator;
1456 int index = str.IndexOf ("<%");
1458 DoParseExpressions (str);
1463 void DoParseExpressions (string str)
1465 int startIndex = 0, index = 0;
1466 Regex codeDirective = new Regex ("(<%(?!@)(?<code>.*?)%>)|(<[\\w:\\.]+.*?runat=[\"']?server[\"']?.*?/>)",
1467 RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
1469 int strLen = str.Length;
1471 while (index > -1 && startIndex < strLen) {
1472 match = codeDirective.Match (str, index);
1474 if (match.Success) {
1475 string value = match.Value;
1476 index = match.Index;
1477 if (index > startIndex)
1478 TextParsed (null, str.Substring (startIndex, index - startIndex));
1480 index += value.Length;
1486 index = str.IndexOf ('<', index);
1491 if (startIndex < strLen)
1492 TextParsed (null, str.Substring (startIndex));
1495 void DoParse (string str)
1497 AspParser parser = new AspParser ("@@nested_tag@@", new StringReader (str));
1498 parser.Error += new ParseErrorHandler (ParseError);
1499 parser.TagParsed += new TagParsedHandler (TagParsed);
1500 parser.TextParsed += new TextParsedHandler (TextParsed);
1504 void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
1507 case TagType.CodeRender:
1508 builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
1511 case TagType.CodeRenderExpression:
1512 builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
1515 case TagType.DataBinding:
1516 builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
1520 case TagType.SelfClosing:
1522 if (generator != null)
1523 generator.TagParsed (location, tagtype, tagid, attributes);
1529 string text = location.PlainText;
1530 if (text != null && text.Trim ().Length > 0)
1531 builder.AppendLiteralString (text);
1536 void TextParsed (ILocation location, string text)
1538 builder.AppendLiteralString (text);
1541 void ParseError (ILocation location, string message)
1543 throw new ParseException (location, message);