Files
mono/mcs/class/System.Web/System.Web.UI/SimpleWebHandlerParser.cs
T
Marek Habersack e71f514f40 2008-01-24 Marek Habersack <[email protected]>
* WebHandlerBuildProvider.cs: derive from the new
	SimpleBuildProvider class.

	* BuildManager.cs: full implementation of the batch compilation
	for the 2.0 profile. The implementation is most probably different
	to MS.NET's but the effects are the same (or nearly the same -
	there are some minor differences). There are missing bits and
	pieces, but minor ones - to be added later.

	* SimpleBuildProvider.cs: new build provider abstract class
	deriving from the GenericBuildProvider that implements common code
	for building web handlers and web services.

	* GenericBuildProvider.cs: new generic abstract class used to
	implement base builder code for all the build provider types and
	maximize code reuse.

	* PageBuildProvider.cs: derive from the new TemplateBuildProvider
	class and implement all the necessary abstract members. 
	Handle "fake" virtual paths, to properly support generating of the
	WSDL helper code.

	* BuildProvider.cs: SetVirtualPath now converts the passed path to
	absolute URL.
	Added internal virtual method GenerateCode, used by derived
	classes.
	SetCommonParameters no longer sets the referenced assemblies, this
	is done in BuildManager now.
	Added an internal virtual property CodeUnit which returns the
	build provider's compilation unit.

	* PageCompiler.cs: fix assignment of base types for asynchronous
	pages, to match MS.NET.
	For asynchronous pages, add the necessary methods generation.

	* BaseCompiler.cs: default namespace is now set using a constant.
	Renamed the Init method into ConstructType, to better reflect its
	purpose and made the method internal - it is used by the build
	providers.
	Added several CreateProvider overloads for easier and more unified
	compilation provider creation.
	Added an internal MainClassType property to enable class type name
	retrieval from other parts of the class hierarchy.

	* ApplicationFileBuildProvider.cs: new build provider deriving
	from the TemplateBuildProvider class to compile the global.asax
	file.

	* AspGenerator.cs: properly handle parsers which have no input
	file path given, but use TextReader instead.
	Dependencies are virtual paths now, convert them to physical ones
	before creating cache dependency.

	* CachingCompiler.cs: parser dependencies are virtual paths now,
	convert them to physical ones before creating cache dependency.

	* AssemblyBuilder.cs: full implementation of the documented
	functionality as well as a lot of internal build code
	added. Produces assemblies using the same style what MS.NET for
	temporary and target file naming. Handles partial type squashing
	if the same partial type is used by several code compile units
	added to the same builder instance.

	* MasterPageBuildProvider.cs: use the new TemplateBuildProvider
	base class and add implementation of all the abstract methods
	required by it.

	* ThemeDirectoryBuildProvider.cs: new build provider to compile
	theme directories. Replaces the old ThemeDirectoryCompiler class.

	* UserControlBuildProvider.cs: use the new TemplateBuildProvider
	base class and add implementation of all the abstract methods
	required by it.

	* TemplateBuildProvider.cs: new internal abstract class which
	implements the common tasks for all the template control build
	providers.

	* WebServiceBuildProvider.cs: use the new SimpleBuildProvider base
	type to implement building.

2008-01-24  Marek Habersack  <[email protected]>

	* PageThemeFileParser.cs: the DefaultBaseType property removed.

	* ApplicationFileParser.cs: added constructor which takes a
	TextReader.
	Removed the DefaultBaseType property.
	Added the Reader property.

	* MasterPage.cs: use BuildManager to create page instance.

	* WebHandlerParser.cs: added a compatibility constructor.

	* TemplateControl.cs: GetTypeFromControlPath uses
	BuildManager.GetCompiledType for the 2.0+ profile.

	* WebServiceParser.cs: added a compatibility internal
	constructor.

	* SimpleWebHandlerParser.cs: properly treat context and
	physicalPath parameters to the constructor, especially for the
	2.0+ profile where they are obsolete.
	Dependencies are added using virtual paths.

	* PageThemeParser.cs: DefaultBaseType property removed.

	* Page.cs: Style sheets and themes are compiled using
	BuildManager.
	Previous page instance is compiled using BuildManager for the 2.0+
	profile.

	* MasterPageParser.cs: Use BuildManager to create instance and
	compile types.
	Dependencies are added using virtual paths.

	* SimpleHandlerFactory.cs: Use
	BuildManager.CreateInstanceFromVirtualPath for the 2.0+ profile.

	* UserControlParser.cs: if the parser is created using a
	TextReader, take the input file path from the virtual path.
	Added a new internal constructor which takes both a TextReader and
	an inputFile parameters.
	Set base type to the default in the constructors.
	Use virtual path when setting master page dependency.
	DefaultBaseTypename doesn't use a literal string in the 2.0+
	profile, it gets the base type from the application
	configuration.

	* TemplateControlParser.cs: Dependency on a control/page mentioned
	in the Reference directive is registered using the virtual path.
	TextReader property is an override now.

	* TemplateParser.cs: RegisterCustomControl adds a dependency on
	the virtual path, not the physical path. The custom control is
	compiled using BuildManager.GetCompiledType for the 2.0+ profile.
	RegisterNamespace does not add a dependency on the assembly.
	LoadType does not add a dependency on the assembly.
	Legacy Src attribute is handled properly now.
	Dependency on code-behind (Src and CodeFile directive attributes)
	is added using the code-behind file's virtual path.
	GetAssemblyFromSource adds a dependency using the virtual path.
	DefaultBaseType implemented here, using DefaultBaseTypeName which
	is implemented in the descendant classes.
	Added internal CodeBehindSource property, used by build
	providers.
	ClassName property works correctly if inputFile is missing
	(e.g. when the parser has been created using a TextReader)
	Added a virtual internal property TextReader to return the readed
	which has been used to create the parser instance.

	* PageHandlerFactory.cs: GetHandler uses
	BuildManager.CreateInstanceFromVirtualPath for the 2.0+ profile.

	* PageParser.cs: set the default base type in the constructors.
	If the input file is not passed to a constructor, take the input
	file path from the virtual path.
	GetCompiledPageInstance uses BuildManager.CreateInstanceFromVirtualPath
	for the 2.0+ profile.
	MasterPage dependency is set using the virtual path of the master
	page.
	MasterPage is compiled into a type using BuildManager.GetCompiledType.
	GetCompiledPageType uses BuildManager.GetCompiledType for the 2.0
	profile.
	DefaultBaseType override removed, it is implemented in the
	TemplateParser class.
	DefaultBaseTypename doesn't use a literal string in the 2.0+
	profile, it gets the base type from the application
	configuration.

2008-01-24  Marek Habersack  <[email protected]>

	* HttpApplicationFactory.cs: use BuildManager.GetCompiledType to
	build the application (global.asax) file.

svn path=/trunk/mcs/; revision=93848
2008-01-24 21:55:44 +00:00

578 lines
15 KiB
C#

//
// System.Web.UI.SimpleWebHandlerParser
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
//
// (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
// Copyright (C) 2005 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.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Util;
namespace System.Web.UI
{
// CAS
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public abstract class SimpleWebHandlerParser
{
HttpContext context;
string vPath;
string physPath;
string className;
bool debug;
string language;
string program;
bool gotDefault;
ArrayList assemblies;
ArrayList dependencies;
Hashtable anames;
string privateBinPath;
string baseDir;
string baseVDir;
#if !NET_2_0
CompilationConfiguration compilationConfig;
#else
TextReader reader;
#endif
int appAssemblyIndex = -1;
Type cachedType;
protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
{
cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
if (cachedType != null)
return; // We don't need anything else.
// context is obsolete in 2.0+ - MSDN recommends passing null, so we need to
// take that into account
if (context != null)
this.context = context;
else
this.context = HttpContext.Current;
this.vPath = virtualPath;
AddDependency (virtualPath);
// physicalPath is obsolete in 2.0+ - same note what for context applies here
if (physicalPath != null && physicalPath.Length > 0)
this.physPath = physicalPath;
else {
HttpRequest req = this.context != null ? context.Request : null;
if (req != null)
this.physPath = req.MapPath (virtualPath);
}
assemblies = new ArrayList ();
string location = Context.ApplicationInstance.AssemblyLocation;
if (location != typeof (TemplateParser).Assembly.Location)
appAssemblyIndex = assemblies.Add (location);
#if NET_2_0
bool addAssembliesInBin = false;
foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
if (info.Assembly == "*")
addAssembliesInBin = true;
else
AddAssemblyByName (info.Assembly, null);
}
if (addAssembliesInBin)
AddAssembliesInBin ();
#else
assemblies.AddRange (CompilationConfig.Assemblies);
if (CompilationConfig.AssembliesInBin)
AddAssembliesInBin ();
#endif
language = CompilationConfig.DefaultLanguage;
GetDirectivesAndContent ();
}
#if NET_2_0
internal SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath, TextReader reader)
: this (context, virtualPath, physicalPath)
{
this.reader = reader;
}
#endif
protected Type GetCompiledTypeFromCache ()
{
return cachedType;
}
void GetDirectivesAndContent ()
{
string line;
bool directiveFound = false;
bool inDirective = false;
StringBuilder directive = null;
StringBuilder content = new StringBuilder ();
int idxStart, idxEnd, length;
using (StreamReader reader = new StreamReader (File.OpenRead (physPath))) {
while ((line = reader.ReadLine ()) != null && cachedType == null) {
length = line.Length;
if (length == 0) {
content.Append ("\n");
continue;
}
idxStart = line.IndexOf ("<%");
if (idxStart > -1) {
idxEnd = line.IndexOf ("%>");
if (idxStart > 0)
content.Append (line.Substring (0, idxStart));
if (directive == null)
directive = new StringBuilder ();
else
directive.Length = 0;
if (idxEnd > -1) {
directiveFound = true;
inDirective = false;
directive.Append (line.Substring (idxStart, idxEnd - idxStart + 2));
if (idxEnd < length - 2)
content.Append (line.Substring (idxEnd + 2, length - idxEnd - 2));
} else {
inDirective = true;
directiveFound = false;
directive.Append (line.Substring (idxStart));
continue;
}
}
if (inDirective) {
int idx = line.IndexOf ("%>");
if (idx > -1) {
directive.Append (line.Substring (0, idx + 2));
if (idx < length)
content.Append (line.Substring (idx + 2) + "\n");
inDirective = false;
directiveFound = true;
} else {
directive.Append (line);
continue;
}
}
if (directiveFound) {
ParseDirective (directive.ToString ());
directiveFound = false;
if (gotDefault) {
cachedType = CachingCompiler.GetTypeFromCache (physPath);
if (cachedType != null)
break;
}
continue;
}
content.Append (line + "\n");
}
directive = null;
}
if (!gotDefault)
throw new ParseException (null, "No @" + DefaultDirectiveName +
" directive found");
if (cachedType == null)
this.program = content.ToString ();
}
void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
{
if (tagtype != System.Web.Compilation.TagType.Directive)
throw new ParseException (location, "Unexpected tag");
if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
AddDefaultDirective (location, attributes);
} else if (String.Compare (tagid, "Assembly", true) == 0) {
AddAssemblyDirective (location, attributes);
} else {
throw new ParseException (location, "Unexpected directive: " + tagid);
}
}
void TextParsed (ILocation location, string text)
{
if (text.Trim () != "")
throw new ParseException (location, "Text not allowed here");
}
void ParseError (ILocation location, string message)
{
throw new ParseException (location, message);
}
static string GetAndRemove (Hashtable table, string key)
{
string o = table [key] as string;
table.Remove (key);
return o;
}
void ParseDirective (string line)
{
AspParser parser = new AspParser (physPath, new StringReader (line));
parser.Error += new ParseErrorHandler (ParseError);
parser.TagParsed += new TagParsedHandler (TagParsed);
parser.TextParsed += new TextParsedHandler (TextParsed);
parser.Parse ();
}
internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
{
#if NET_2_0
CompilationSection compConfig;
#else
CompilationConfiguration compConfig;
#endif
compConfig = CompilationConfig;
if (gotDefault)
throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
gotDefault = true;
Hashtable attributes = attrs.GetDictionary (null);
className = GetAndRemove (attributes, "class");
if (className == null)
throw new ParseException (null, "No Class attribute found.");
string d = GetAndRemove (attributes, "debug");
if (d != null) {
debug = (String.Compare (d, "true", true) == 0);
if (debug == false && String.Compare (d, "false", true) != 0)
throw new ParseException (null, "Invalid value for Debug attribute");
} else
debug = compConfig.Debug;
language = GetAndRemove (attributes, "language");
if (language == null)
language = compConfig.DefaultLanguage;
GetAndRemove (attributes, "codebehind");
if (attributes.Count > 0)
throw new ParseException (location, "Unrecognized attribute in " +
DefaultDirectiveName + " directive");
}
internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
{
Hashtable tbl = attrs.GetDictionary (null);
string name = GetAndRemove (tbl, "Name");
string src = GetAndRemove (tbl, "Src");
if (name == null && src == null)
throw new ParseException (location, "You gotta specify Src or Name");
if (name != null && src != null)
throw new ParseException (location, "Src and Name cannot be used together");
if (name != null) {
AddAssemblyByName (name, location);
} else {
GetAssemblyFromSource (src, location);
}
if (tbl.Count > 0)
throw new ParseException (location, "Unrecognized attribute in Assembly directive");
}
internal virtual void AddAssembly (Assembly assembly, bool fullPath)
{
if (assembly == null)
throw new ArgumentNullException ("assembly");
if (anames == null)
anames = new Hashtable ();
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 AddAssemblyByName (string name, ILocation location)
{
if (anames == null)
anames = new Hashtable ();
if (anames.Contains (name)) {
object o = anames [name];
if (o is string)
o = anames [o];
return (Assembly) o;
}
Assembly assembly = LoadAssemblyFromBin (name);
if (assembly != null) {
AddAssembly (assembly, true);
return assembly;
}
Exception ex = null;
try {
assembly = Assembly.LoadWithPartialName (name);
} catch (Exception e) {
ex = null;
assembly = null;
}
if (assembly == null)
throw new ParseException (location, String.Format ("Assembly '{0}' not found", name), ex);
AddAssembly (assembly, true);
return assembly;
}
void AddAssembliesInBin ()
{
foreach (string s in HttpApplication.BinDirectoryAssemblies) {
try {
Assembly assembly = Assembly.LoadFrom (s);
AddAssembly (assembly, true);
} catch (Exception e) {
throw new Exception ("Error while loading " + s, e);
}
}
}
Assembly LoadAssemblyFromBin (string name)
{
Assembly assembly = null;
foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
string fn = Path.GetFileName (dll);
fn = Path.ChangeExtension (fn, null);
if (fn != name)
continue;
assembly = Assembly.LoadFrom (dll);
return assembly;
}
return null;
}
Assembly GetAssemblyFromSource (string vpath, ILocation location)
{
vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
string realPath = context.Request.MapPath (vpath);
if (!File.Exists (realPath))
throw new ParseException (location, "File " + vpath + " not found");
AddDependency (vpath);
CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
if (result.NativeCompilerReturnValue != 0) {
StreamReader reader = new StreamReader (realPath);
throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
}
AddAssembly (result.CompiledAssembly, true);
return result.CompiledAssembly;
}
internal Type GetTypeFromBin (string tname)
{
if (tname == null || tname.Length == 0)
throw new ArgumentNullException ("tname");
Type result = null;
string typeName;
string assemblyName;
int comma = tname.IndexOf (',');
if (comma != -1) {
typeName = tname.Substring (0, comma).Trim ();
assemblyName = tname.Substring (comma + 1).Trim ();
} else {
typeName = tname;
assemblyName = null;
}
Type type = null;
Assembly assembly = null;
if (assemblyName != null) {
assembly = Assembly.Load (assemblyName);
if (assembly != null)
type = assembly.GetType (typeName, false);
if (type != null)
return type;
}
#if NET_2_0
IList toplevelAssemblies = BuildManager.TopLevelAssemblies;
if (toplevelAssemblies != null && toplevelAssemblies.Count > 0) {
foreach (Assembly asm in toplevelAssemblies) {
type = asm.GetType (typeName, false);
if (type != null) {
if (result != null)
throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
result = type;
}
}
}
#endif
foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
assembly = Assembly.LoadFrom (dll);
type = assembly.GetType (typeName, false);
if (type != null) {
if (result != null)
throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
result = type;
}
}
if (result == null)
throw new HttpException (String.Format ("Type {0} not found.", typeName));
return result;
}
internal virtual void AddDependency (string filename)
{
if (dependencies == null)
dependencies = new ArrayList ();
if (!dependencies.Contains (filename))
dependencies.Add (filename);
}
// Properties
protected abstract string DefaultDirectiveName { get; }
internal HttpContext Context {
get { return context; }
}
internal string VirtualPath {
get { return vPath; }
}
internal string PhysicalPath {
get { return physPath; }
}
internal string ClassName {
get { return className; }
}
internal bool Debug {
get { return debug; }
}
internal string Language {
get { return language; }
}
internal string Program {
get { return program; }
}
internal ArrayList Assemblies {
get {
if (appAssemblyIndex != -1) {
object o = assemblies [appAssemblyIndex];
assemblies.RemoveAt (appAssemblyIndex);
assemblies.Add (o);
appAssemblyIndex = -1;
}
return assemblies;
}
}
internal ArrayList Dependencies {
get { return dependencies; }
}
internal string BaseDir {
get {
if (baseDir == null)
baseDir = context.Request.MapPath (BaseVirtualDir);
return baseDir;
}
}
internal virtual string BaseVirtualDir {
get {
if (baseVDir == null)
baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
return baseVDir;
}
}
#if NET_2_0
CompilationSection CompilationConfig {
get {
return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
}
}
internal TextReader Reader {
get { return reader; }
set { reader = value; }
}
#else
internal CompilationConfiguration CompilationConfig {
get {
if (compilationConfig == null)
compilationConfig = CompilationConfiguration.GetInstance (context);
return compilationConfig;
}
}
#endif
}
}