Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.Web.Compilation;
namespace System.Web.WebPages.Razor
{
internal sealed class AssemblyBuilderWrapper : IAssemblyBuilder
{
public AssemblyBuilderWrapper(AssemblyBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
InnerBuilder = builder;
}
internal AssemblyBuilder InnerBuilder { get; set; }
public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit)
{
InnerBuilder.AddCodeCompileUnit(buildProvider, compileUnit);
}
public void GenerateTypeFactory(string typeName)
{
InnerBuilder.GenerateTypeFactory(typeName);
}
}
}

View File

@ -0,0 +1,16 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Web.WebPages.Razor
{
public class CompilingPathEventArgs : EventArgs
{
public CompilingPathEventArgs(string virtualPath, WebPageRazorHost host)
{
VirtualPath = virtualPath;
Host = host;
}
public string VirtualPath { get; private set; }
public WebPageRazorHost Host { get; set; }
}
}

View File

@ -0,0 +1,31 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Configuration;
namespace System.Web.WebPages.Razor.Configuration
{
public class HostSection : ConfigurationSection
{
public static readonly string SectionName = RazorWebSectionGroup.GroupName + "/host";
private static readonly ConfigurationProperty _typeProperty =
new ConfigurationProperty("factoryType",
typeof(string),
null,
ConfigurationPropertyOptions.IsRequired);
private bool _factoryTypeSet = false;
private string _factoryType;
[ConfigurationProperty("factoryType", IsRequired = true, DefaultValue = null)]
public string FactoryType
{
get { return _factoryTypeSet ? _factoryType : (string)this[_typeProperty]; }
set
{
_factoryType = value;
_factoryTypeSet = true;
}
}
}
}

View File

@ -0,0 +1,54 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Web.Configuration;
namespace System.Web.WebPages.Razor.Configuration
{
public class RazorPagesSection : ConfigurationSection
{
public static readonly string SectionName = RazorWebSectionGroup.GroupName + "/pages";
private static readonly ConfigurationProperty _pageBaseTypeProperty =
new ConfigurationProperty("pageBaseType",
typeof(string),
null,
ConfigurationPropertyOptions.IsRequired);
private static readonly ConfigurationProperty _namespacesProperty =
new ConfigurationProperty("namespaces",
typeof(NamespaceCollection),
null,
ConfigurationPropertyOptions.IsRequired);
private bool _pageBaseTypeSet = false;
private bool _namespacesSet = false;
private string _pageBaseType;
private NamespaceCollection _namespaces;
[ConfigurationProperty("pageBaseType", IsRequired = true)]
public string PageBaseType
{
get { return _pageBaseTypeSet ? _pageBaseType : (string)this[_pageBaseTypeProperty]; }
set
{
_pageBaseType = value;
_pageBaseTypeSet = true;
}
}
[ConfigurationProperty("namespaces", IsRequired = true)]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Being able to set this property is extremely useful for third-parties who are testing components which interact with the Razor configuration system")]
public NamespaceCollection Namespaces
{
get { return _namespacesSet ? _namespaces : (NamespaceCollection)this[_namespacesProperty]; }
set
{
_namespaces = value;
_namespacesSet = true;
}
}
}
}

View File

@ -0,0 +1,40 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Configuration;
namespace System.Web.WebPages.Razor.Configuration
{
public class RazorWebSectionGroup : ConfigurationSectionGroup
{
public static readonly string GroupName = "system.web.webPages.razor";
// Use flags instead of null values since tests may want to set the property to null
private bool _hostSet = false;
private bool _pagesSet = false;
private HostSection _host;
private RazorPagesSection _pages;
[ConfigurationProperty("host", IsRequired = false)]
public HostSection Host
{
get { return _hostSet ? _host : (HostSection)Sections["host"]; }
set
{
_host = value;
_hostSet = true;
}
}
[ConfigurationProperty("pages", IsRequired = false)]
public RazorPagesSection Pages
{
get { return _pagesSet ? _pages : (RazorPagesSection)Sections["pages"]; }
set
{
_pages = value;
_pagesSet = true;
}
}
}
}

View File

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click
// "In Project Suppression File".
// You do not need to add suppressions to this file manually.

View File

@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web.Hosting;
namespace System.Web.WebPages.Razor
{
internal sealed class HostingEnvironmentWrapper : IHostingEnvironment
{
public string MapPath(string virtualPath)
{
return HostingEnvironment.MapPath(virtualPath);
}
}
}

View File

@ -0,0 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.Web.Compilation;
namespace System.Web.WebPages.Razor
{
internal interface IAssemblyBuilder
{
void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit);
void GenerateTypeFactory(string typeName);
}
}

View File

@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Web.WebPages.Razor
{
internal interface IHostingEnvironment
{
string MapPath(string virtualPath);
}
}

View File

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.ComponentModel;
using System.Web.Compilation;
namespace System.Web.WebPages.Razor
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class PreApplicationStartCode
{
// NOTE: Do not add public fields, methods, or other members to this class.
// This class does not show up in Intellisense so members on it will not be
// discoverable by users. Place new members on more appropriate classes that
// relate to the public API (for example, a LoginUrl property should go on a
// membership-related class).
private static bool _startWasCalled;
public static void Start()
{
// Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from
// another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the
// order so we have to guard against multiple calls.
// All Start calls are made on same thread, so no lock needed here.
if (_startWasCalled)
{
return;
}
_startWasCalled = true;
BuildProvider.RegisterBuildProvider(".cshtml", typeof(RazorBuildProvider));
BuildProvider.RegisterBuildProvider(".vbhtml", typeof(RazorBuildProvider));
}
}
}

View File

@ -0,0 +1,15 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.WebPages.Razor;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Web.WebPages.Razor")]
[assembly: AssemblyDescription("")]
[assembly: InternalsVisibleTo("System.Web.WebPages.Razor.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")]

View File

@ -0,0 +1,254 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security;
using System.Web.Compilation;
using System.Web.Razor;
using System.Web.Razor.Generator;
using System.Web.Razor.Parser.SyntaxTree;
namespace System.Web.WebPages.Razor
{
[BuildProviderAppliesTo(BuildProviderAppliesTo.Web | BuildProviderAppliesTo.Code)]
public class RazorBuildProvider : BuildProvider
{
private static bool? _isFullTrust;
private CodeCompileUnit _generatedCode = null;
private WebPageRazorHost _host = null;
private IList _virtualPathDependencies;
private IAssemblyBuilder _assemblyBuilder;
public static event EventHandler<CodeGenerationCompleteEventArgs> CodeGenerationCompleted;
internal event EventHandler<CodeGenerationCompleteEventArgs> CodeGenerationCompletedInternal
{
add { _codeGenerationCompletedInternal += value; }
remove { _codeGenerationCompletedInternal -= value; }
}
public static event EventHandler CodeGenerationStarted;
/// <summary>
/// For unit testing.
/// </summary>
internal event EventHandler CodeGenerationStartedInternal
{
add { _codeGenerationStartedInternal += value; }
remove { _codeGenerationStartedInternal -= value; }
}
public static event EventHandler<CompilingPathEventArgs> CompilingPath;
/// <summary>
/// For unit testing
/// </summary>
private event EventHandler<CodeGenerationCompleteEventArgs> _codeGenerationCompletedInternal;
private event EventHandler _codeGenerationStartedInternal;
internal WebPageRazorHost Host
{
get
{
if (_host == null)
{
_host = CreateHost();
}
return _host;
}
set { _host = value; }
}
// Returns the base dependencies and any dependencies added via AddVirtualPathDependencies
public override ICollection VirtualPathDependencies
{
get
{
if (_virtualPathDependencies != null)
{
// Return a readonly wrapper so as to prevent users from modifying the collection directly.
return ArrayList.ReadOnly(_virtualPathDependencies);
}
else
{
return base.VirtualPathDependencies;
}
}
}
public new string VirtualPath
{
get { return base.VirtualPath; }
}
public AssemblyBuilder AssemblyBuilder
{
get
{
var wrapper = _assemblyBuilder as AssemblyBuilderWrapper;
if (wrapper != null)
{
return wrapper.InnerBuilder;
}
else
{
return null;
}
}
}
// For unit testing
internal IAssemblyBuilder AssemblyBuilderInternal
{
get { return _assemblyBuilder; }
}
internal CodeCompileUnit GeneratedCode
{
get
{
EnsureGeneratedCode();
return _generatedCode;
}
set { _generatedCode = value; }
}
public override CompilerType CodeCompilerType
{
get
{
EnsureGeneratedCode();
CompilerType compilerType = GetDefaultCompilerTypeForLanguage(Host.CodeLanguage.LanguageName);
if (_isFullTrust != false && Host.DefaultDebugCompilation)
{
try
{
SetIncludeDebugInfoFlag(compilerType);
_isFullTrust = true;
}
catch (SecurityException)
{
_isFullTrust = false;
}
}
return compilerType;
}
}
public void AddVirtualPathDependency(string dependency)
{
if (_virtualPathDependencies == null)
{
// Initialize the collection containing the base dependencies
_virtualPathDependencies = new ArrayList(base.VirtualPathDependencies);
}
_virtualPathDependencies.Add(dependency);
}
public override Type GetGeneratedType(CompilerResults results)
{
return results.CompiledAssembly.GetType(String.Format(CultureInfo.CurrentCulture, "{0}.{1}", Host.DefaultNamespace, Host.DefaultClassName));
}
public override void GenerateCode(AssemblyBuilder assemblyBuilder)
{
GenerateCodeCore(new AssemblyBuilderWrapper(assemblyBuilder));
}
internal virtual void GenerateCodeCore(IAssemblyBuilder assemblyBuilder)
{
OnCodeGenerationStarted(assemblyBuilder);
assemblyBuilder.AddCodeCompileUnit(this, GeneratedCode);
assemblyBuilder.GenerateTypeFactory(String.Format(CultureInfo.InvariantCulture, "{0}.{1}", Host.DefaultNamespace, Host.DefaultClassName));
}
protected internal virtual TextReader InternalOpenReader()
{
return OpenReader();
}
protected internal virtual WebPageRazorHost CreateHost()
{
// Get the host from config
WebPageRazorHost configuredHost = GetHostFromConfig();
// Fire the event
CompilingPathEventArgs args = new CompilingPathEventArgs(VirtualPath, configuredHost);
OnBeforeCompilePath(args);
// Return the host provided in the args, which may have been changed by the handler
return args.Host;
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method performs significant work and a property would not be appropriate")]
protected internal virtual WebPageRazorHost GetHostFromConfig()
{
return WebRazorHostFactory.CreateHostFromConfig(VirtualPath);
}
protected virtual void OnBeforeCompilePath(CompilingPathEventArgs args)
{
EventHandler<CompilingPathEventArgs> handler = CompilingPath;
if (handler != null)
{
handler(this, args);
}
}
private void OnCodeGenerationStarted(IAssemblyBuilder assemblyBuilder)
{
_assemblyBuilder = assemblyBuilder;
EventHandler handler = _codeGenerationStartedInternal ?? CodeGenerationStarted;
if (handler != null)
{
handler(this, null);
}
}
private void OnCodeGenerationCompleted(CodeCompileUnit generatedCode)
{
EventHandler<CodeGenerationCompleteEventArgs> handler = _codeGenerationCompletedInternal ?? CodeGenerationCompleted;
if (handler != null)
{
handler(this, new CodeGenerationCompleteEventArgs(Host.VirtualPath, Host.PhysicalPath, generatedCode));
}
}
private void EnsureGeneratedCode()
{
if (_generatedCode == null)
{
RazorTemplateEngine engine = new RazorTemplateEngine(Host);
GeneratorResults results = null;
using (TextReader reader = InternalOpenReader())
{
results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: Host.PhysicalPath);
}
if (!results.Success)
{
throw CreateExceptionFromParserError(results.ParserErrors.Last(), VirtualPath);
}
_generatedCode = results.GeneratedCode;
// Run the code gen complete event
OnCodeGenerationCompleted(_generatedCode);
}
}
private static HttpParseException CreateExceptionFromParserError(RazorError error, string virtualPath)
{
return new HttpParseException(error.Message + Environment.NewLine, null, virtualPath, null, error.Location.LineIndex + 1);
}
[SuppressMessage("Microsoft.Security", "CA2141:TransparentMethodsMustNotSatisfyLinkDemandsFxCopRule", Justification = "We are catching the SecurityException to detect medium trust")]
private static void SetIncludeDebugInfoFlag(CompilerType compilerType)
{
compilerType.CompilerParameters.IncludeDebugInformation = true;
}
}
}

View File

@ -0,0 +1,81 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace System.Web.WebPages.Razor.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class RazorWebResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal RazorWebResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.Web.WebPages.Razor.Resources.RazorWebResources", typeof(RazorWebResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Could not determine the code language for &quot;{0}&quot;..
/// </summary>
internal static string BuildProvider_No_CodeLanguageService_For_Path {
get {
return ResourceManager.GetString("BuildProvider_No_CodeLanguageService_For_Path", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not locate Razor Host Factory type: {0}.
/// </summary>
internal static string Could_Not_Locate_FactoryType {
get {
return ResourceManager.GetString("Could_Not_Locate_FactoryType", resourceCulture);
}
}
}
}

View File

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="BuildProvider_No_CodeLanguageService_For_Path" xml:space="preserve">
<value>Could not determine the code language for "{0}".</value>
</data>
<data name="Could_Not_Locate_FactoryType" xml:space="preserve">
<value>Could not locate Razor Host Factory type: {0}</value>
</data>
</root>

View File

@ -0,0 +1,113 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<CodeAnalysis Condition=" '$(CodeAnalysis)' == '' ">false</CodeAnalysis>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>System.Web.WebPages.Razor</RootNamespace>
<AssemblyName>System.Web.WebPages.Razor</AssemblyName>
<FileAlignment>512</FileAlignment>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;ASPNETWEBPAGES</DefineConstants>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\bin\Release\</OutputPath>
<DefineConstants>TRACE;ASPNETWEBPAGES</DefineConstants>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'CodeCoverage|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\..\bin\CodeCoverage\</OutputPath>
<DefineConstants>TRACE;DEBUG;CODE_COVERAGE;ASPNETWEBPAGES</DefineConstants>
<DebugType>full</DebugType>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\CommonAssemblyInfo.cs">
<Link>Properties\CommonAssemblyInfo.cs</Link>
</Compile>
<Compile Include="..\CommonResources.Designer.cs">
<Link>Common\CommonResources.Designer.cs</Link>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>CommonResources.resx</DependentUpon>
</Compile>
<Compile Include="..\GlobalSuppressions.cs">
<Link>Common\GlobalSuppressions.cs</Link>
</Compile>
<Compile Include="..\TransparentCommonAssemblyInfo.cs">
<Link>Properties\TransparentCommonAssemblyInfo.cs</Link>
</Compile>
<Compile Include="AssemblyBuilderWrapper.cs" />
<Compile Include="CompilingPathEventArgs.cs" />
<Compile Include="Configuration\HostSection.cs" />
<Compile Include="Configuration\RazorPagesSection.cs" />
<Compile Include="Configuration\RazorWebSectionGroup.cs" />
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="HostingEnvironmentWrapper.cs" />
<Compile Include="IAssemblyBuilder.cs" />
<Compile Include="IHostingEnvironment.cs" />
<Compile Include="PreApplicationStartCode.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RazorBuildProvider.cs" />
<Compile Include="WebRazorHostFactory.cs" />
<Compile Include="WebCodeRazorHost.cs" />
<Compile Include="WebPageRazorHost.cs" />
<Compile Include="Resources\RazorWebResources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>RazorWebResources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\System.Web.WebPages\System.Web.WebPages.csproj">
<Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>
<Name>System.Web.WebPages</Name>
</ProjectReference>
<ProjectReference Include="..\System.Web.Razor\System.Web.Razor.csproj">
<Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>
<Name>System.Web.Razor</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\CommonResources.resx">
<Link>Common\CommonResources.resx</Link>
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>CommonResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="Resources\RazorWebResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>RazorWebResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<CodeAnalysisDictionary Include="..\CodeAnalysisDictionary.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,101 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Web.Razor.Generator;
using System.Web.Razor.Parser;
namespace System.Web.WebPages.Razor
{
public class WebCodeRazorHost : WebPageRazorHost
{
private const string AppCodeDir = "App_Code";
private const string HttpContextAccessorName = "Context";
private static readonly string _helperPageBaseType = typeof(HelperPage).FullName;
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "The code path is safe, it is a property setter and not dependent on other state")]
public WebCodeRazorHost(string virtualPath)
: base(virtualPath)
{
DefaultBaseClass = _helperPageBaseType;
DefaultNamespace = DetermineNamespace(virtualPath);
DefaultDebugCompilation = false;
StaticHelpers = true;
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "The code path is safe, it is a property setter and not dependent on other state")]
public WebCodeRazorHost(string virtualPath, string physicalPath)
: base(virtualPath, physicalPath)
{
DefaultBaseClass = _helperPageBaseType;
DefaultNamespace = DetermineNamespace(virtualPath);
DefaultDebugCompilation = false;
StaticHelpers = true;
}
public override void PostProcessGeneratedCode(CodeGeneratorContext context)
{
base.PostProcessGeneratedCode(context);
// Yank out the execute method (ignored in Razor Web Code pages)
context.GeneratedClass.Members.Remove(context.TargetMethod);
// Make ApplicationInstance static
CodeMemberProperty appInstanceProperty =
context.GeneratedClass.Members
.OfType<CodeMemberProperty>()
.Where(p => ApplicationInstancePropertyName
.Equals(p.Name))
.SingleOrDefault();
if (appInstanceProperty != null)
{
appInstanceProperty.Attributes |= MemberAttributes.Static;
}
}
protected override string GetClassName(string virtualPath)
{
return ParserHelpers.SanitizeClassName(Path.GetFileNameWithoutExtension(virtualPath));
}
private static string DetermineNamespace(string virtualPath)
{
// Normailzize the virtual path
virtualPath = virtualPath.Replace(Path.DirectorySeparatorChar, '/');
// Get the directory
virtualPath = GetDirectory(virtualPath);
// Skip the App_Code segment if any
int appCodeIndex = virtualPath.IndexOf(AppCodeDir, StringComparison.OrdinalIgnoreCase);
if (appCodeIndex != -1)
{
virtualPath = virtualPath.Substring(appCodeIndex + AppCodeDir.Length);
}
// Get the segments removing any empty entries
IEnumerable<string> segments = virtualPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (!segments.Any())
{
return WebDefaultNamespace;
}
return WebDefaultNamespace + "." + String.Join(".", segments);
}
private static string GetDirectory(string virtualPath)
{
int lastSlash = virtualPath.LastIndexOf('/');
if (lastSlash != -1)
{
return virtualPath.Substring(0, lastSlash);
}
return String.Empty;
}
}
}

View File

@ -0,0 +1,353 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web.Compilation;
using System.Web.Hosting;
using System.Web.Razor;
using System.Web.Razor.Generator;
using System.Web.Razor.Parser;
using System.Web.WebPages.Instrumentation;
using System.Web.WebPages.Razor.Resources;
using Microsoft.Internal.Web.Utils;
namespace System.Web.WebPages.Razor
{
public class WebPageRazorHost : RazorEngineHost
{
// DevDiv Bug 941404 - Add a prefix and folder name to class names
internal const string PageClassNamePrefix = "_Page_";
internal const string ApplicationInstancePropertyName = "ApplicationInstance";
internal const string ContextPropertyName = "Context";
internal const string DefineSectionMethodName = "DefineSection";
internal const string WebDefaultNamespace = "ASP";
internal const string WriteToMethodName = "WriteTo";
internal const string WriteLiteralToMethodName = "WriteLiteralTo";
internal const string BeginContextMethodName = "BeginContext";
internal const string EndContextMethodName = "EndContext";
internal const string ResolveUrlMethodName = "Href";
private const string ApplicationStartFileName = "_AppStart";
private const string PageStartFileName = "_PageStart";
internal static readonly string FallbackApplicationTypeName = typeof(HttpApplication).FullName;
internal static readonly string PageBaseClass = typeof(WebPage).FullName;
internal static readonly string TemplateTypeName = typeof(HelperResult).FullName;
private static ConcurrentDictionary<string, object> _importedNamespaces = new ConcurrentDictionary<string, object>();
private readonly Dictionary<string, string> _specialFileBaseTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private string _className;
private RazorCodeLanguage _codeLanguage;
private string _globalAsaxTypeName;
private bool? _isSpecialPage;
private string _physicalPath = null;
private string _specialFileBaseClass;
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "The code path is safe, it is a property setter and not dependent on other state")]
private WebPageRazorHost()
{
NamespaceImports.Add("System");
NamespaceImports.Add("System.Collections.Generic");
NamespaceImports.Add("System.IO");
NamespaceImports.Add("System.Linq");
NamespaceImports.Add("System.Net");
NamespaceImports.Add("System.Web");
NamespaceImports.Add("System.Web.Helpers");
NamespaceImports.Add("System.Web.Security");
NamespaceImports.Add("System.Web.UI");
NamespaceImports.Add("System.Web.WebPages");
NamespaceImports.Add("System.Web.WebPages.Html");
RegisterSpecialFile(ApplicationStartFileName, typeof(ApplicationStartPage));
RegisterSpecialFile(PageStartFileName, typeof(StartPage));
DefaultNamespace = WebDefaultNamespace;
GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
GeneratedClassContext.DefaultWriteMethodName,
GeneratedClassContext.DefaultWriteLiteralMethodName,
WriteToMethodName,
WriteLiteralToMethodName,
TemplateTypeName,
DefineSectionMethodName,
BeginContextMethodName,
EndContextMethodName)
{
ResolveUrlMethodName = ResolveUrlMethodName
};
DefaultPageBaseClass = PageBaseClass;
DefaultDebugCompilation = true;
EnableInstrumentation = false;
}
public WebPageRazorHost(string virtualPath)
: this(virtualPath, null)
{
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "The code path is safe, it is a property setter and not dependent on other state")]
public WebPageRazorHost(string virtualPath, string physicalPath)
: this()
{
if (String.IsNullOrEmpty(virtualPath))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "virtualPath"), "virtualPath");
}
VirtualPath = virtualPath;
PhysicalPath = physicalPath;
DefaultClassName = GetClassName(VirtualPath);
CodeLanguage = GetCodeLanguage();
EnableInstrumentation = new InstrumentationService().IsAvailable;
}
public override RazorCodeLanguage CodeLanguage
{
get
{
if (_codeLanguage == null)
{
_codeLanguage = GetCodeLanguage();
}
return _codeLanguage;
}
protected set { _codeLanguage = value; }
}
public override string DefaultBaseClass
{
get
{
if (base.DefaultBaseClass != null)
{
return base.DefaultBaseClass;
}
if (IsSpecialPage)
{
return SpecialPageBaseClass;
}
else
{
return DefaultPageBaseClass;
}
}
set { base.DefaultBaseClass = value; }
}
public override string DefaultClassName
{
get
{
if (_className == null)
{
_className = GetClassName(VirtualPath);
}
return _className;
}
set { _className = value; }
}
public bool DefaultDebugCompilation { get; set; }
public string DefaultPageBaseClass { get; set; }
internal string GlobalAsaxTypeName
{
get { return _globalAsaxTypeName ?? (HostingEnvironment.IsHosted ? BuildManager.GetGlobalAsaxType().FullName : FallbackApplicationTypeName); }
set { _globalAsaxTypeName = value; }
}
public bool IsSpecialPage
{
get
{
CheckForSpecialPage();
return _isSpecialPage.Value;
}
}
public string PhysicalPath
{
get
{
MapPhysicalPath();
return _physicalPath;
}
set { _physicalPath = value; }
}
public override string InstrumentedSourceFilePath
{
get { return VirtualPath; }
set { VirtualPath = value; }
}
private string SpecialPageBaseClass
{
get
{
CheckForSpecialPage();
return _specialFileBaseClass;
}
}
public string VirtualPath { get; private set; }
public static void AddGlobalImport(string ns)
{
if (String.IsNullOrEmpty(ns))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "ns"), "ns");
}
_importedNamespaces.TryAdd(ns, null);
}
private void CheckForSpecialPage()
{
if (!_isSpecialPage.HasValue)
{
string fileName = Path.GetFileNameWithoutExtension(VirtualPath);
string baseType;
if (_specialFileBaseTypes.TryGetValue(fileName, out baseType))
{
_isSpecialPage = true;
_specialFileBaseClass = baseType;
}
else
{
_isSpecialPage = false;
}
}
}
public override ParserBase CreateMarkupParser()
{
return new HtmlMarkupParser();
}
private static RazorCodeLanguage DetermineCodeLanguage(string fileName)
{
string extension = Path.GetExtension(fileName);
// Use an if rather than else-if just in case Path.GetExtension returns null for some reason
if (String.IsNullOrEmpty(extension))
{
return null;
}
if (extension[0] == '.')
{
extension = extension.Substring(1); // Trim off the dot
}
// Look up the language
// At the moment this only deals with code languages: cs, vb, etc., but in theory we could have MarkupLanguageServices which allow for
// interesting combinations like: vbcss, csxml, etc.
RazorCodeLanguage language = GetLanguageByExtension(extension);
return language;
}
protected virtual string GetClassName(string virtualPath)
{
// Remove "~/" and run through our santizer
// For example, for ~/Foo/Bar/Baz.cshtml, the class name is _Page_Foo_Bar_Baz_cshtml
return ParserHelpers.SanitizeClassName(PageClassNamePrefix + virtualPath.TrimStart('~', '/'));
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Method involves significant processing and should not be a property")]
protected virtual RazorCodeLanguage GetCodeLanguage()
{
RazorCodeLanguage language = DetermineCodeLanguage(VirtualPath);
if (language == null && !String.IsNullOrEmpty(PhysicalPath))
{
language = DetermineCodeLanguage(PhysicalPath);
}
if (language == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, RazorWebResources.BuildProvider_No_CodeLanguageService_For_Path, VirtualPath));
}
return language;
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method involves copying memory, so a property is not appropriate")]
public static IEnumerable<string> GetGlobalImports()
{
return _importedNamespaces.ToArray().Select(pair => pair.Key);
}
private static RazorCodeLanguage GetLanguageByExtension(string extension)
{
return RazorCodeLanguage.GetLanguageByExtension(extension);
}
private void MapPhysicalPath()
{
if (_physicalPath == null && HostingEnvironment.IsHosted)
{
string path = HostingEnvironment.MapPath(VirtualPath);
if (!String.IsNullOrEmpty(path) && File.Exists(path))
{
_physicalPath = path;
}
}
}
public override void PostProcessGeneratedCode(CodeGeneratorContext context)
{
base.PostProcessGeneratedCode(context);
// Add additional global imports
context.Namespace.Imports.AddRange(GetGlobalImports().Select(s => new CodeNamespaceImport(s)).ToArray());
// Create ApplicationInstance property
CodeMemberProperty prop = new CodeMemberProperty()
{
Name = ApplicationInstancePropertyName,
Type = new CodeTypeReference(GlobalAsaxTypeName),
HasGet = true,
HasSet = false,
Attributes = MemberAttributes.Family | MemberAttributes.Final
};
prop.GetStatements.Add(
new CodeMethodReturnStatement(
new CodeCastExpression(
new CodeTypeReference(GlobalAsaxTypeName),
new CodePropertyReferenceExpression(
new CodePropertyReferenceExpression(
null,
ContextPropertyName),
ApplicationInstancePropertyName))));
context.GeneratedClass.Members.Insert(0, prop);
}
protected void RegisterSpecialFile(string fileName, Type baseType)
{
if (baseType == null)
{
throw new ArgumentNullException("baseType");
}
RegisterSpecialFile(fileName, baseType.FullName);
}
protected void RegisterSpecialFile(string fileName, string baseTypeName)
{
if (String.IsNullOrEmpty(fileName))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "fileName"), "fileName");
}
if (String.IsNullOrEmpty(baseTypeName))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "baseTypeName"), "baseTypeName");
}
_specialFileBaseTypes[fileName] = baseTypeName;
}
}
}

View File

@ -0,0 +1,177 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.WebPages.Razor.Configuration;
using System.Web.WebPages.Razor.Resources;
using Microsoft.Internal.Web.Utils;
namespace System.Web.WebPages.Razor
{
public class WebRazorHostFactory
{
private static ConcurrentDictionary<string, Func<WebRazorHostFactory>> _factories =
new ConcurrentDictionary<string, Func<WebRazorHostFactory>>(StringComparer.OrdinalIgnoreCase);
internal static Func<string, Type> TypeFactory = DefaultTypeFactory;
public static WebPageRazorHost CreateDefaultHost(string virtualPath)
{
return CreateDefaultHost(virtualPath, null);
}
public static WebPageRazorHost CreateDefaultHost(string virtualPath, string physicalPath)
{
return CreateHostFromConfigCore(null, virtualPath, physicalPath);
}
public static WebPageRazorHost CreateHostFromConfig(string virtualPath)
{
return CreateHostFromConfig(virtualPath, null);
}
public static WebPageRazorHost CreateHostFromConfig(string virtualPath, string physicalPath)
{
if (String.IsNullOrEmpty(virtualPath))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "virtualPath"), "virtualPath");
}
return CreateHostFromConfigCore(GetRazorSection(virtualPath), virtualPath, physicalPath);
}
public static WebPageRazorHost CreateHostFromConfig(RazorWebSectionGroup config, string virtualPath)
{
return CreateHostFromConfig(config, virtualPath, null);
}
public static WebPageRazorHost CreateHostFromConfig(RazorWebSectionGroup config, string virtualPath, string physicalPath)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
if (String.IsNullOrEmpty(virtualPath))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "virtualPath"), "virtualPath");
}
return CreateHostFromConfigCore(config, virtualPath, physicalPath);
}
internal static WebPageRazorHost CreateHostFromConfigCore(RazorWebSectionGroup config, string virtualPath, string physicalPath)
{
// Use the virtual path to select a host environment for the generated code
// Do this check here because the App_Code host can't be overridden.
// Make the path app relative
virtualPath = EnsureAppRelative(virtualPath);
WebPageRazorHost host;
if (virtualPath.StartsWith("~/App_Code", StringComparison.OrdinalIgnoreCase))
{
// Under App_Code => It's a Web Code file
host = new WebCodeRazorHost(virtualPath, physicalPath);
}
else
{
WebRazorHostFactory factory = null;
if (config != null && config.Host != null && !String.IsNullOrEmpty(config.Host.FactoryType))
{
Func<WebRazorHostFactory> factoryCreator = _factories.GetOrAdd(config.Host.FactoryType, CreateFactory);
Debug.Assert(factoryCreator != null); // CreateFactory should throw if there's an error creating the factory
factory = factoryCreator();
}
host = (factory ?? new WebRazorHostFactory()).CreateHost(virtualPath, physicalPath);
if (config != null && config.Pages != null)
{
ApplyConfigurationToHost(config.Pages, host);
}
}
return host;
}
private static Func<WebRazorHostFactory> CreateFactory(string typeName)
{
Type factoryType = TypeFactory(typeName);
if (factoryType == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
RazorWebResources.Could_Not_Locate_FactoryType,
typeName));
}
return Expression.Lambda<Func<WebRazorHostFactory>>(Expression.New(factoryType))
.Compile();
}
public static void ApplyConfigurationToHost(RazorPagesSection config, WebPageRazorHost host)
{
host.DefaultPageBaseClass = config.PageBaseType;
// Add imports
foreach (string import in config.Namespaces.OfType<NamespaceInfo>().Select(ns => ns.Namespace))
{
host.NamespaceImports.Add(import);
}
}
public virtual WebPageRazorHost CreateHost(string virtualPath, string physicalPath)
{
return new WebPageRazorHost(virtualPath, physicalPath);
}
internal static RazorWebSectionGroup GetRazorSection(string virtualPath)
{
// Get the individual sections (we can only use GetSection in medium trust) and then reconstruct the section group
return new RazorWebSectionGroup()
{
Host = (HostSection)WebConfigurationManager.GetSection(HostSection.SectionName, virtualPath),
Pages = (RazorPagesSection)WebConfigurationManager.GetSection(RazorPagesSection.SectionName, virtualPath)
};
}
#if CODE_COVERAGE
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// JUSTIFICATION: VirtualPathUtility.ToAppRelative is only available in ASP.Net environment
#endif
private static string EnsureAppRelative(string virtualPath)
{
if (HostingEnvironment.IsHosted)
{
virtualPath = VirtualPathUtility.ToAppRelative(virtualPath);
}
else
{
if (virtualPath.StartsWith("/", StringComparison.Ordinal))
{
virtualPath = "~" + virtualPath;
}
else if (!virtualPath.StartsWith("~/", StringComparison.Ordinal))
{
virtualPath = "~/" + virtualPath;
}
}
return virtualPath;
}
#if CODE_COVERAGE
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// JUSTIFICATION: BuildManager.GetType is only available in ASP.Net environment
#endif
private static Type DefaultTypeFactory(string typeName)
{
return BuildManager.GetType(typeName, false, false);
}
}
}