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,53 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Globalization;
using System.IO;
using System.Web.WebPages.Resources;
using Microsoft.Web.Infrastructure;
namespace System.Web.WebPages
{
internal static class BuildManagerExceptionUtil
{
// Checks the exception to see if it is from CompilationUtil.GetBuildProviderTypeFromExtension, which will throw
// an exception about an unsupported extension.
// Actual error format: There is no build provider registered for the extension '.txt'. You can register one in the <compilation><buildProviders> section in machine.config or web.config. Make sure is has a BuildProviderAppliesToAttribute attribute which includes the value 'Web' or 'All'.
internal static bool IsUnsupportedExtensionError(HttpException e)
{
Exception exception = e;
// Go through the layers of exceptions to find if any of them is from GetBuildProviderTypeFromExtension
while (exception != null)
{
var site = exception.TargetSite;
if (site != null && site.Name == "GetBuildProviderTypeFromExtension" && site.DeclaringType != null && site.DeclaringType.Name == "CompilationUtil")
{
return true;
}
exception = exception.InnerException;
}
return false;
}
internal static void ThrowIfUnsupportedExtension(string virtualPath, HttpException e)
{
if (IsUnsupportedExtensionError(e))
{
var extension = Path.GetExtension(virtualPath);
throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));
}
}
internal static void ThrowIfCodeDomDefinedExtension(string virtualPath, HttpException e)
{
if (e is HttpCompileException)
{
var extension = Path.GetExtension(virtualPath);
if (InfrastructureHelper.IsCodeDomDefinedExtension(extension))
{
throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));
}
}
}
}
}

View File

@@ -0,0 +1,75 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
namespace System.Web.WebPages
{
internal static class CultureUtil
{
internal static void SetCulture(Thread thread, HttpContextBase context, string cultureName)
{
Debug.Assert(!String.IsNullOrEmpty(cultureName));
CultureInfo cultureInfo = GetCulture(context, cultureName);
if (cultureInfo != null)
{
thread.CurrentCulture = cultureInfo;
}
}
internal static void SetUICulture(Thread thread, HttpContextBase context, string cultureName)
{
Debug.Assert(!String.IsNullOrEmpty(cultureName));
CultureInfo cultureInfo = GetCulture(context, cultureName);
if (cultureInfo != null)
{
thread.CurrentUICulture = cultureInfo;
}
}
private static CultureInfo GetCulture(HttpContextBase context, string cultureName)
{
if (cultureName.Equals("auto", StringComparison.OrdinalIgnoreCase))
{
return DetermineAutoCulture(context);
}
else
{
return CultureInfo.GetCultureInfo(cultureName);
}
}
private static CultureInfo DetermineAutoCulture(HttpContextBase context)
{
HttpRequestBase request = context.Request;
Debug.Assert(request != null); //This call is made from a WebPageExecutingBase. Request can never be null when inside a page.
CultureInfo culture = null;
if (request.UserLanguages != null)
{
string userLanguageEntry = request.UserLanguages.FirstOrDefault();
if (!String.IsNullOrWhiteSpace(userLanguageEntry))
{
// Check if user language has q parameter. E.g. something like this: "as-IN;q=0.3"
int index = userLanguageEntry.IndexOf(';');
if (index != -1)
{
userLanguageEntry = userLanguageEntry.Substring(0, index);
}
try
{
culture = new CultureInfo(userLanguageEntry);
}
catch (CultureNotFoundException)
{
// There is no easy way to ask if a given culture is invalid so we have to handle exception.
}
}
}
return culture;
}
}
}

View File

@@ -0,0 +1,75 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
namespace System.Web.WebPages
{
internal static class PathUtil
{
/// <summary>
/// Path.GetExtension performs a CheckInvalidPathChars(path) which blows up for paths that do not translate to valid physical paths but are valid paths in ASP.NET
/// This method is a near clone of Path.GetExtension without a call to CheckInvalidPathChars(path);
/// </summary>
internal static string GetExtension(string path)
{
if (String.IsNullOrEmpty(path))
{
return path;
}
int current = path.Length;
while (--current >= 0)
{
char ch = path[current];
if (ch == '.')
{
if (current == path.Length - 1)
{
break;
}
return path.Substring(current);
}
if (ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar)
{
break;
}
}
return String.Empty;
}
internal static bool IsWithinAppRoot(string appDomainAppVirtualPath, string virtualPath)
{
if (appDomainAppVirtualPath == null)
{
// If the runtime has not been initialized, just return true.
return true;
}
var absPath = virtualPath;
if (!VirtualPathUtility.IsAbsolute(absPath))
{
absPath = VirtualPathUtility.ToAbsolute(absPath);
}
// We need to call this overload because it returns null if the path is not within the application root.
// The overload calls into MakeVirtualPathAppRelative(string virtualPath, string applicationPath, bool nullIfNotInApp), with
// nullIfNotInApp set to true.
return VirtualPathUtility.ToAppRelative(absPath, appDomainAppVirtualPath) != null;
}
/// <summary>
/// Determines true if the path is simply "MyPath", and not app-relative "~/MyPath" or absolute "/MyApp/MyPath" or relative "../Test/MyPath"
/// </summary>
/// <returns>True if it is a not app-relative, absolute or relative.</returns>
internal static bool IsSimpleName(string path)
{
if (VirtualPathUtility.IsAbsolute(path) || VirtualPathUtility.IsAppRelative(path))
{
return false;
}
if (path.StartsWith(".", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,83 @@
// 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.Web.Razor;
using System.Web.SessionState;
using System.Web.WebPages.Resources;
namespace System.Web.WebPages
{
internal static class SessionStateUtil
{
private static readonly ConcurrentDictionary<Type, SessionStateBehavior?> _sessionStateBehaviorCache = new ConcurrentDictionary<Type, SessionStateBehavior?>();
internal static void SetUpSessionState(HttpContextBase context, IHttpHandler handler)
{
SetUpSessionState(context, handler, _sessionStateBehaviorCache);
}
internal static void SetUpSessionState(HttpContextBase context, IHttpHandler handler, ConcurrentDictionary<Type, SessionStateBehavior?> cache)
{
WebPageHttpHandler webPageHandler = handler as WebPageHttpHandler;
Debug.Assert(handler != null);
SessionStateBehavior? sessionState = GetSessionStateBehavior(webPageHandler.RequestedPage, cache);
if (sessionState != null)
{
// If the page explicitly specifies a session state value, return since it has the most priority.
context.SetSessionStateBehavior(sessionState.Value);
return;
}
WebPageRenderingBase page = webPageHandler.StartPage;
StartPage startPage = null;
do
{
// Drill down _AppStart and _PageStart.
startPage = page as StartPage;
if (startPage != null)
{
sessionState = GetSessionStateBehavior(page, cache);
page = startPage.ChildPage;
}
}
while (startPage != null);
if (sessionState != null)
{
context.SetSessionStateBehavior(sessionState.Value);
}
}
private static SessionStateBehavior? GetSessionStateBehavior(WebPageExecutingBase page, ConcurrentDictionary<Type, SessionStateBehavior?> cache)
{
return cache.GetOrAdd(page.GetType(), type =>
{
SessionStateBehavior sessionStateBehavior = SessionStateBehavior.Default;
var attributes = (RazorDirectiveAttribute[])type.GetCustomAttributes(typeof(RazorDirectiveAttribute), inherit: false);
var directiveAttributes = attributes.Where(attr => StringComparer.OrdinalIgnoreCase.Equals("sessionstate", attr.Name))
.ToList();
if (!directiveAttributes.Any())
{
return null;
}
if (directiveAttributes.Count > 1)
{
throw new InvalidOperationException(WebPageResources.SessionState_TooManyValues);
}
var directiveAttribute = directiveAttributes[0];
if (!Enum.TryParse<SessionStateBehavior>(directiveAttribute.Value, ignoreCase: true, result: out sessionStateBehavior))
{
var values = Enum.GetValues(typeof(SessionStateBehavior)).Cast<SessionStateBehavior>().Select(s => s.ToString());
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, WebPageResources.SessionState_InvalidValue,
directiveAttribute.Value, page.VirtualPath, String.Join(", ", values)));
}
return sessionStateBehavior;
});
}
}
}

View File

@@ -0,0 +1,47 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web.Routing;
namespace System.Web.WebPages
{
internal static class TypeHelper
{
/// <summary>
/// Given an object of anonymous type, add each property as a key and associated with its value to a dictionary.
/// </summary>
internal static IDictionary<string, object> ObjectToDictionary(object value)
{
return new RouteValueDictionary(value);
}
/// <summary>
/// Given an object of anonymous type, add each property as a key and associated with its value to the given dictionary.
/// </summary>
internal static void AddAnonymousObjectToDictionary(IDictionary<string, object> dictionary, object value)
{
var values = ObjectToDictionary(value);
foreach (var item in values)
{
dictionary.Add(item);
}
}
/// <remarks>This code is copied from http://www.liensberger.it/web/blog/?p=191 </remarks>
internal static bool IsAnonymousType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
// TODO: The only way to detect anonymous types right now.
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}
}
}

View File

@@ -0,0 +1,71 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Globalization;
using System.Text;
using System.Web.Routing;
namespace System.Web.WebPages
{
internal static class UrlUtil
{
internal static string Url(string basePath, string path, params object[] pathParts)
{
if (basePath != null)
{
path = VirtualPathUtility.Combine(basePath, path);
}
// Make sure it's not a ~/ path, which the client couldn't handle
path = VirtualPathUtility.ToAbsolute(path);
return BuildUrl(path, pathParts);
}
internal static string BuildUrl(string path, params object[] pathParts)
{
path = HttpUtility.UrlPathEncode(path);
StringBuilder queryString = new StringBuilder();
foreach (var pathPart in pathParts)
{
Type partType = pathPart.GetType();
if (IsDisplayableType(partType))
{
var displayablePath = Convert.ToString(pathPart, CultureInfo.InvariantCulture);
path += "/" + HttpUtility.UrlPathEncode(displayablePath);
}
else
{
// If it smells like an anonymous object, treat it as query string name/value pairs instead of path info parts
// REVIEW: this is hacky!
var dictionary = new RouteValueDictionary(pathPart);
foreach (var item in dictionary)
{
if (queryString.Length == 0)
{
queryString.Append('?');
}
else
{
queryString.Append('&');
}
string stringValue = Convert.ToString(item.Value, CultureInfo.InvariantCulture);
queryString.Append(HttpUtility.UrlEncode(item.Key))
.Append('=')
.Append(HttpUtility.UrlEncode(stringValue));
}
}
}
return path + queryString;
}
private static bool IsDisplayableType(Type t)
{
// If it doesn't support any interfaces (e.g. IFormattable), we probably can't display it. It's likely an anonymous type.
// REVIEW: this is hacky!
return t.GetInterfaces().Length > 0;
}
}
}