public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir, ClientBuildManagerParameter parameter, TypeDescriptionProvider typeDescriptionProvider) { this._lock = new object(); if (parameter == null) { parameter = new ClientBuildManagerParameter(); } this.InitializeCBMTDPBridge(typeDescriptionProvider); if (!string.IsNullOrEmpty(appPhysicalTargetDir)) { parameter.PrecompilationFlags |= PrecompilationFlags.Clean; } this._hostingParameters = new HostingEnvironmentParameters(); this._hostingParameters.HostingFlags = HostingEnvironmentFlags.ClientBuildManager | HostingEnvironmentFlags.DontCallAppInitialize; this._hostingParameters.ClientBuildManagerParameter = parameter; this._hostingParameters.PrecompilationTargetPhysicalDirectory = appPhysicalTargetDir; if (typeDescriptionProvider != null) { this._hostingParameters.HostingFlags |= HostingEnvironmentFlags.SupportsMultiTargeting; } if (appVirtualDir[0] != '/') { appVirtualDir = "/" + appVirtualDir; } if (((appPhysicalSourceDir == null) && appVirtualDir.StartsWith("/IISExpress/", StringComparison.OrdinalIgnoreCase)) && (appVirtualDir.Length > "/IISExpress/".Length)) { int index = appVirtualDir.IndexOf('/', "/IISExpress/".Length); if (index > 0) { this._hostingParameters.IISExpressVersion = appVirtualDir.Substring("/IISExpress/".Length, index - "/IISExpress/".Length); appVirtualDir = appVirtualDir.Substring(index); } } this.Initialize(VirtualPath.CreateNonRelative(appVirtualDir), appPhysicalSourceDir); }
public void StartAppDomainProtocolListenerChannel(string appId, string protocolId, IListenerChannelCallback listenerChannelCallback) { try { if (appId == null) { throw new ArgumentNullException("appId"); } if (protocolId == null) { throw new ArgumentNullException("protocolId"); } ISAPIApplicationHost appHostParameter = this.CreateAppHost(appId, null); Type appDomainProtocolHandlerType = this.GetAppDomainProtocolHandlerType(protocolId); AppDomainProtocolHandler handler = null; LockableAppDomainContext lockableAppDomainContext = this._appManager.GetLockableAppDomainContext(appId); lock (lockableAppDomainContext) { HostingEnvironmentParameters hostingParameters = new HostingEnvironmentParameters { HostingFlags = HostingEnvironmentFlags.ThrowHostingInitErrors }; this.PreloadApplicationIfRequired(appId, appHostParameter, hostingParameters, lockableAppDomainContext); handler = (AppDomainProtocolHandler)this._appManager.CreateObjectInternal(appId, appDomainProtocolHandlerType, appHostParameter, false, hostingParameters); ListenerAdapterDispatchShim shim = (ListenerAdapterDispatchShim)this._appManager.CreateObjectInternal(appId, typeof(ListenerAdapterDispatchShim), appHostParameter, false, hostingParameters); if (shim == null) { throw new HttpException(System.Web.SR.GetString("Failure_Create_Listener_Shim")); } shim.StartListenerChannel(handler, listenerChannelCallback); ((IRegisteredObject)shim).Stop(true); } } catch (Exception exception) { using (new ProcessImpersonationContext()) { Misc.ReportUnhandledException(exception, new string[] { System.Web.SR.GetString("Failure_Start_AppDomain_Listener") }); } throw; } }
internal void Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) { _hostingParameters = hostingParameters; HostingEnvironmentFlags hostingFlags = HostingEnvironmentFlags.Default; if (_hostingParameters != null) { hostingFlags = _hostingParameters.HostingFlags; if (_hostingParameters.IISExpressVersion != null) { ServerConfig.IISExpressVersion = _hostingParameters.IISExpressVersion; } } // Keep track of the app manager, unless HideFromAppManager flag was passed if ((hostingFlags & HostingEnvironmentFlags.HideFromAppManager) == 0) _appManager = appManager; if ((hostingFlags & HostingEnvironmentFlags.ClientBuildManager) != 0) { BuildManagerHost.InClientBuildManager = true; } if ((hostingFlags & HostingEnvironmentFlags.SupportsMultiTargeting) != 0) { BuildManagerHost.SupportsMultiTargeting = true; } // // init config system using private config if applicable // if (appHost is ISAPIApplicationHost && !ServerConfig.UseMetabase) { string rootWebConfigPath = ((ISAPIApplicationHost)appHost).ResolveRootWebConfigPath(); if (!String.IsNullOrEmpty(rootWebConfigPath)) { Debug.Assert(File.Exists(rootWebConfigPath), "File.Exists(rootWebConfigPath)"); HttpConfigurationSystem.RootWebConfigurationFilePath = rootWebConfigPath; } // we need to explicit create a COM proxy in this app domain // so we don't go back to the default domain or have lifetime issues // remember support functions IProcessHostSupportFunctions proxyFunctions = ((ISAPIApplicationHost)appHost).SupportFunctions; if (null != proxyFunctions) { _functions = Misc.CreateLocalSupportFunctions(proxyFunctions); } } _appId = HttpRuntime.AppDomainAppId; _appVirtualPath = HttpRuntime.AppDomainAppVirtualPathObject; _appPhysicalPath = HttpRuntime.AppDomainAppPathInternal; _appHost = appHost; _configMapPath = configMapPathFactory.Create(_appVirtualPath.VirtualPathString, _appPhysicalPath); HttpConfigurationSystem.EnsureInit(_configMapPath, true, false); // attempt to cache and use IConfigMapPath2 provider // which supports VirtualPath's to save on conversions _configMapPath2 = _configMapPath as IConfigMapPath2; _initiateShutdownWorkItemCallback = new WaitCallback(this.InitiateShutdownWorkItemCallback); // notify app manager if (_appManager != null) { _appManager.HostingEnvironmentActivated(CacheMemorySizePressure.EffectiveProcessMemoryLimit); } // make sure there is always app host if (_appHost == null) { _appHost = new SimpleApplicationHost(_appVirtualPath, _appPhysicalPath); } else { _externalAppHost = true; } // remember the token to access config _configToken = _appHost.GetConfigToken(); // Start with a MapPath based virtual path provider _mapPathBasedVirtualPathProvider = new MapPathBasedVirtualPathProvider(); _virtualPathProvider = _mapPathBasedVirtualPathProvider; // initiaze HTTP-independent features HttpRuntime.InitializeHostingFeatures(hostingFlags, policyLevel, appDomainCreationException); // VSWhidbey 393259. Do not monitor idle timeout for CBM since Venus // will always restart a new appdomain if old one is shutdown. if (!BuildManagerHost.InClientBuildManager) { // start monitoring for idle inside app domain StartMonitoringForIdleTimeout(); } // notify app manager if the app domain limit is violated EnforceAppDomainLimit(); // get application identity (for explicit impersonation mode) GetApplicationIdentity(); // call AppInitialize, unless the flag says not to do it (e.g. CBM scenario). // Also, don't call it if HostingInit failed (VSWhidbey 210495) if(!HttpRuntime.HostingInitFailed) { try { BuildManager.ExecutePreAppStart(); if ((hostingFlags & HostingEnvironmentFlags.DontCallAppInitialize) == 0) { BuildManager.CallAppInitializeMethod(); } } catch (Exception e) { // could throw compilation errors in 'code' - report them with first http request HttpRuntime.InitializationException = e; if ((hostingFlags & HostingEnvironmentFlags.ThrowHostingInitErrors) != 0) { throw; } } } }
// // Initialization // // called from app manager right after app domain (and hosting env) is created internal void Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel) { Initialize(appManager, appHost, configMapPathFactory, hostingParameters, policyLevel, null); }
// // Precompilation related code // internal void SetPrecompilationInfo(HostingEnvironmentParameters hostingParameters) { if (hostingParameters == null || hostingParameters.ClientBuildManagerParameter == null) return; _precompilationFlags = hostingParameters.ClientBuildManagerParameter.PrecompilationFlags; _strongNameKeyFile = hostingParameters.ClientBuildManagerParameter.StrongNameKeyFile; _strongNameKeyContainer = hostingParameters.ClientBuildManagerParameter.StrongNameKeyContainer; // Check if we're precompiling to a target directory _precompTargetPhysicalDir = hostingParameters.PrecompilationTargetPhysicalDirectory; if (_precompTargetPhysicalDir == null) return; // Check if the target dir already exists and is not empty if (Util.IsNonEmptyDirectory(_precompTargetPhysicalDir)) { // If it's not empty and OverwriteTarget is off, fail if ((_precompilationFlags & PrecompilationFlags.OverwriteTarget) == 0) { throw new HttpException(SR.GetString(SR.Dir_not_empty)); } // Does it contain the precomp marker file bool updatable; bool precompiled = ReadPrecompMarkerFile(_precompTargetPhysicalDir, out updatable); // If not, refuse to delete the directory, even if OverwriteTarget is on (VSWhidbey 425095) if (!precompiled) { throw new HttpException(SR.GetString(SR.Dir_not_empty_not_precomp)); } // The OverwriteTarget flag was specified, so delete the directory if (!DeletePrecompTargetDirectory()) { // If we failed to delete it, sleep 250 ms and try again, in case there is // an appdomain in the process of shutting down (the shut down would // have been triggered by the first delete attempt) Debug.Trace("BuildManager", "Failed to delete " + _precompTargetPhysicalDir + ". Sleeping and trying once more..."); Thread.Sleep(250); if (!DeletePrecompTargetDirectory()) { Debug.Trace("BuildManager", "Failed to delete " + _precompTargetPhysicalDir + ". Sleeping and trying once more..."); // Try again after 1 second. Thread.Sleep(1000); // If we still couldn't delete it, fail if (!DeletePrecompTargetDirectory()) { throw new HttpException(SR.GetString(SR.Cant_delete_dir)); } } } } // Create a marker file to mark the fact that this is a precompiled app CreatePrecompMarkerFile(); }
/* * Creates an instance of the PrecompilationManager. * appPhysicalSourceDir points to the physical root of the application (e.g "c:\myapp") * appVirtualDir is the virtual path to the app root. It can be anything (e.g. "/dummy"), * but ideally it should match the path later given to Cassini, in order for * compilation that happens here to be reused there. * appPhysicalTargetDir is the directory where the precompiled site is placed * typeDescriptionProvider is the provider used for retrieving type * information for multi-targeting */ public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir, ClientBuildManagerParameter parameter, TypeDescriptionProvider typeDescriptionProvider) { if (parameter == null) { parameter = new ClientBuildManagerParameter(); } InitializeCBMTDPBridge(typeDescriptionProvider); // Always build clean in precompilation for deployment mode, // since building incrementally raises all kind of issues (VSWhidbey 382954). if (!String.IsNullOrEmpty(appPhysicalTargetDir)) { parameter.PrecompilationFlags |= PrecompilationFlags.Clean; } _hostingParameters = new HostingEnvironmentParameters(); _hostingParameters.HostingFlags = HostingEnvironmentFlags.DontCallAppInitialize | HostingEnvironmentFlags.ClientBuildManager; _hostingParameters.ClientBuildManagerParameter = parameter; _hostingParameters.PrecompilationTargetPhysicalDirectory = appPhysicalTargetDir; if (typeDescriptionProvider != null) { _hostingParameters.HostingFlags |= HostingEnvironmentFlags.SupportsMultiTargeting; } // Make sure the app virtual dir starts with / if (appVirtualDir[0] != '/') appVirtualDir = "/" + appVirtualDir; if (appPhysicalSourceDir == null && appVirtualDir.StartsWith(IISExpressPrefix, StringComparison.OrdinalIgnoreCase) && appVirtualDir.Length > IISExpressPrefix.Length) { // appVirtualDir should have the form "/IISExpress/<version>/LM/W3SVC/", // and we will try to extract the version. The version will be validated // when it is passed to IISVersionHelper..ctor. int endSlash = appVirtualDir.IndexOf('/', IISExpressPrefix.Length); if (endSlash > 0) { _hostingParameters.IISExpressVersion = appVirtualDir.Substring(IISExpressPrefix.Length, endSlash - IISExpressPrefix.Length); appVirtualDir = appVirtualDir.Substring(endSlash); } } Initialize(VirtualPath.CreateNonRelative(appVirtualDir), appPhysicalSourceDir); }
private HostingEnvironment CreateAppDomainWithHostingEnvironment(string appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters) { string physicalPath = appHost.GetPhysicalPath(); if (!System.Web.Util.StringUtil.StringEndsWith(physicalPath, Path.DirectorySeparatorChar)) { physicalPath = physicalPath + Path.DirectorySeparatorChar; } string domainId = ConstructAppDomainId(appId); string appName = System.Web.Util.StringUtil.GetStringHashCode(appId.ToLower(CultureInfo.InvariantCulture) + physicalPath.ToLower(CultureInfo.InvariantCulture)).ToString("x", CultureInfo.InvariantCulture); VirtualPath appVPath = VirtualPath.Create(appHost.GetVirtualPath()); IDictionary dict = new Hashtable(20); AppDomainSetup setup = new AppDomainSetup(); PopulateDomainBindings(domainId, appId, appName, physicalPath, appVPath, setup, dict); AppDomain domain = null; Exception innerException = null; string siteID = appHost.GetSiteID(); string virtualPathStringNoTrailingSlash = appVPath.VirtualPathStringNoTrailingSlash; bool flag = false; bool flag2 = false; System.Configuration.Configuration configuration = null; PolicyLevel policyLevel = null; PermissionSet grantSet = null; List<StrongName> list = new List<StrongName>(); string[] strArray = new string[] { "System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293", "System.Web.Extensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.Abstractions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.Routing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.ComponentModel.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.DynamicData, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.DataVisualization, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.ApplicationServices, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" }; Exception appDomainCreationException = null; ImpersonationContext context = null; IntPtr zero = IntPtr.Zero; if ((hostingParameters != null) && ((hostingParameters.HostingFlags & HostingEnvironmentFlags.ClientBuildManager) != HostingEnvironmentFlags.Default)) { flag2 = true; setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; } try { zero = appHost.GetConfigToken(); if (zero != IntPtr.Zero) { context = new ImpersonationContext(zero); } try { if (flag2 && (hostingParameters.IISExpressVersion != null)) { grantSet = new PermissionSet(PermissionState.Unrestricted); setup.PartialTrustVisibleAssemblies = strArray; } else { if (appHost is ISAPIApplicationHost) { string key = "f" + siteID + appVPath.VirtualPathString; MapPathCacheInfo info1 = (MapPathCacheInfo) HttpRuntime.CacheInternal.Remove(key); configuration = WebConfigurationManager.OpenWebConfiguration(virtualPathStringNoTrailingSlash, siteID); } else { WebConfigurationFileMap fileMap = new WebConfigurationFileMap(); IConfigMapPath path2 = appHost.GetConfigMapPathFactory().Create(appVPath.VirtualPathString, physicalPath); string directory = null; string baseName = null; string path = "/"; path2.GetPathConfigFilename(siteID, path, out directory, out baseName); if (directory != null) { fileMap.VirtualDirectories.Add(path, new VirtualDirectoryMapping(Path.GetFullPath(directory), true)); } foreach (string str10 in virtualPathStringNoTrailingSlash.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)) { path = path + str10; path2.GetPathConfigFilename(siteID, path, out directory, out baseName); if (directory != null) { fileMap.VirtualDirectories.Add(path, new VirtualDirectoryMapping(Path.GetFullPath(directory), true)); } path = path + "/"; } configuration = WebConfigurationManager.OpenMappedWebConfiguration(fileMap, virtualPathStringNoTrailingSlash, siteID); } TrustSection trustSection = (TrustSection) configuration.GetSection("system.web/trust"); if ((trustSection == null) || string.IsNullOrEmpty(trustSection.Level)) { throw new ConfigurationErrorsException(System.Web.SR.GetString("Config_section_not_present", new object[] { "trust" })); } bool legacyCasModel = trustSection.LegacyCasModel; if (legacyCasModel) { SetNetFx40LegacySecurityPolicy(setup); } if (flag2) { grantSet = new PermissionSet(PermissionState.Unrestricted); setup.PartialTrustVisibleAssemblies = strArray; } else { flag = legacyCasModel; if (!flag) { if (trustSection.Level == "Full") { grantSet = new PermissionSet(PermissionState.Unrestricted); setup.PartialTrustVisibleAssemblies = strArray; } else { SecurityPolicySection section = (SecurityPolicySection) configuration.GetSection("system.web/securityPolicy"); CompilationSection compilationSection = (CompilationSection) configuration.GetSection("system.web/compilation"); FullTrustAssembliesSection section4 = (FullTrustAssembliesSection) configuration.GetSection("system.web/fullTrustAssemblies"); policyLevel = GetPartialTrustPolicyLevel(trustSection, section, compilationSection, physicalPath, appVPath); grantSet = policyLevel.GetNamedPermissionSet(trustSection.PermissionSetName); if (grantSet == null) { throw new ConfigurationErrorsException(System.Web.SR.GetString("Permission_set_not_found", new object[] { trustSection.PermissionSetName })); } if (section4 != null) { FullTrustAssemblyCollection fullTrustAssemblies = section4.FullTrustAssemblies; if (fullTrustAssemblies != null) { list.AddRange(from fta in fullTrustAssemblies.Cast<FullTrustAssembly>() select CreateStrongName(fta.AssemblyName, fta.Version, fta.PublicKey)); } } if (list.Contains(_mwiV1StrongName)) { list.AddRange(CreateFutureMicrosoftWebInfrastructureStrongNames()); } setup.AppDomainManagerType = typeof(AspNetAppDomainManager).FullName; setup.AppDomainManagerAssembly = typeof(AspNetAppDomainManager).Assembly.FullName; } } if (trustSection.Level != "Full") { PartialTrustVisibleAssembliesSection section5 = (PartialTrustVisibleAssembliesSection) configuration.GetSection("system.web/partialTrustVisibleAssemblies"); string[] array = null; if (section5 != null) { PartialTrustVisibleAssemblyCollection partialTrustVisibleAssemblies = section5.PartialTrustVisibleAssemblies; if ((partialTrustVisibleAssemblies != null) && (partialTrustVisibleAssemblies.Count != 0)) { array = new string[partialTrustVisibleAssemblies.Count + strArray.Length]; for (int i = 0; i < partialTrustVisibleAssemblies.Count; i++) { array[i] = partialTrustVisibleAssemblies[i].AssemblyName + ", PublicKey=" + NormalizePublicKeyBlob(partialTrustVisibleAssemblies[i].PublicKey); } strArray.CopyTo(array, partialTrustVisibleAssemblies.Count); } } if (array == null) { array = strArray; } setup.PartialTrustVisibleAssemblies = array; } } } } catch (Exception exception3) { appDomainCreationException = exception3; grantSet = new PermissionSet(PermissionState.Unrestricted); } try { if (flag) { domain = AppDomain.CreateDomain(domainId, GetDefaultDomainIdentity(), setup); } else { domain = AppDomain.CreateDomain(domainId, GetDefaultDomainIdentity(), setup, grantSet, list.ToArray()); } foreach (DictionaryEntry entry in dict) { domain.SetData((string) entry.Key, (string) entry.Value); } } catch (Exception exception4) { innerException = exception4; } } finally { if (context != null) { context.Undo(); context = null; } if (zero != IntPtr.Zero) { System.Web.UnsafeNativeMethods.CloseHandle(zero); zero = IntPtr.Zero; } } if (domain == null) { throw new SystemException(System.Web.SR.GetString("Cannot_create_AppDomain"), innerException); } Type type = typeof(HostingEnvironment); string fullName = type.Module.Assembly.FullName; string typeName = type.FullName; ObjectHandle handle = null; ImpersonationContext context2 = null; IntPtr token = IntPtr.Zero; int num2 = 10; int num3 = 0; while (num3 < num2) { try { token = appHost.GetConfigToken(); break; } catch (InvalidOperationException) { num3++; Thread.Sleep(250); continue; } } if (token != IntPtr.Zero) { try { context2 = new ImpersonationContext(token); } catch { } finally { System.Web.UnsafeNativeMethods.CloseHandle(token); } } try { handle = Activator.CreateInstance(domain, fullName, typeName); } finally { if (context2 != null) { context2.Undo(); } if (handle == null) { AppDomain.Unload(domain); } } HostingEnvironment environment = (handle != null) ? (handle.Unwrap() as HostingEnvironment) : null; if (environment == null) { throw new SystemException(System.Web.SR.GetString("Cannot_create_HostEnv")); } IConfigMapPathFactory configMapPathFactory = appHost.GetConfigMapPathFactory(); if (appDomainCreationException == null) { environment.Initialize(this, appHost, configMapPathFactory, hostingParameters, policyLevel); return environment; } environment.Initialize(this, appHost, configMapPathFactory, hostingParameters, policyLevel, appDomainCreationException); return environment; }
private HostingEnvironment GetAppDomainWithHostingEnvironment(string appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters) { LockableAppDomainContext lockableAppDomainContext = this.GetLockableAppDomainContext(appId); lock (lockableAppDomainContext) { HostingEnvironment hostEnv = lockableAppDomainContext.HostEnv; if (hostEnv != null) { try { hostEnv.IsUnloaded(); } catch (AppDomainUnloadedException) { hostEnv = null; } } if (hostEnv == null) { hostEnv = this.CreateAppDomainWithHostingEnvironmentAndReportErrors(appId, appHost, hostingParameters); lockableAppDomainContext.HostEnv = hostEnv; Interlocked.Increment(ref this._accessibleHostingEnvCount); } return hostEnv; } }
internal IRegisteredObject CreateObjectWithDefaultAppHostAndAppId(string physicalPath, VirtualPath virtualPath, Type type, out string appId) { HostingEnvironmentParameters hostingParameters = new HostingEnvironmentParameters { HostingFlags = HostingEnvironmentFlags.DontCallAppInitialize }; return this.CreateObjectWithDefaultAppHostAndAppId(physicalPath, virtualPath, type, false, hostingParameters, out appId); }
internal IRegisteredObject CreateObjectInternal(string appId, Type type, IApplicationHost appHost, bool failIfExists, HostingEnvironmentParameters hostingParameters) { if (!typeof(IRegisteredObject).IsAssignableFrom(type)) { throw new ArgumentException(System.Web.SR.GetString("Not_IRegisteredObject", new object[] { type.FullName }), "type"); } ObjectHandle handle = this.GetAppDomainWithHostingEnvironment(appId, appHost, hostingParameters).CreateWellKnownObjectInstance(type.AssemblyQualifiedName, failIfExists); if (handle == null) { return null; } return (handle.Unwrap() as IRegisteredObject); }
public IRegisteredObject CreateObject(string appId, Type type, string virtualPath, string physicalPath, bool failIfExists, bool throwOnError) { if (appId == null) { throw new ArgumentNullException("appId"); } SimpleApplicationHost appHost = new SimpleApplicationHost(VirtualPath.CreateAbsolute(virtualPath), physicalPath); HostingEnvironmentParameters hostingParameters = null; if (throwOnError) { hostingParameters = new HostingEnvironmentParameters { HostingFlags = HostingEnvironmentFlags.ThrowHostingInitErrors }; } return this.CreateObjectInternal(appId, type, appHost, failIfExists, hostingParameters); }
internal ObjectHandle CreateInstanceInNewWorkerAppDomain(Type type, string appId, VirtualPath virtualPath, string physicalPath) { IApplicationHost appHost = new SimpleApplicationHost(virtualPath, physicalPath); HostingEnvironmentParameters hostingParameters = new HostingEnvironmentParameters { HostingFlags = HostingEnvironmentFlags.HideFromAppManager }; return this.CreateAppDomainWithHostingEnvironmentAndReportErrors(appId, appHost, hostingParameters).CreateInstance(type.AssemblyQualifiedName); }
private HostingEnvironment CreateAppDomainWithHostingEnvironmentAndReportErrors(string appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters) { HostingEnvironment environment; try { environment = this.CreateAppDomainWithHostingEnvironment(appId, appHost, hostingParameters); } catch (Exception exception) { Misc.ReportUnhandledException(exception, new string[] { System.Web.SR.GetString("Failed_to_initialize_AppDomain"), appId }); throw; } return environment; }
internal void Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) { this._hostingParameters = hostingParameters; HostingEnvironmentFlags hostingFlags = HostingEnvironmentFlags.Default; if (this._hostingParameters != null) { hostingFlags = this._hostingParameters.HostingFlags; if (this._hostingParameters.IISExpressVersion != null) { ServerConfig.IISExpressVersion = this._hostingParameters.IISExpressVersion; } } if ((hostingFlags & HostingEnvironmentFlags.HideFromAppManager) == HostingEnvironmentFlags.Default) { this._appManager = appManager; } if ((hostingFlags & HostingEnvironmentFlags.ClientBuildManager) != HostingEnvironmentFlags.Default) { BuildManagerHost.InClientBuildManager = true; } if ((hostingFlags & HostingEnvironmentFlags.SupportsMultiTargeting) != HostingEnvironmentFlags.Default) { BuildManagerHost.SupportsMultiTargeting = true; } if ((appHost is ISAPIApplicationHost) && !ServerConfig.UseMetabase) { string str = ((ISAPIApplicationHost) appHost).ResolveRootWebConfigPath(); if (!string.IsNullOrEmpty(str)) { HttpConfigurationSystem.RootWebConfigurationFilePath = str; } IProcessHostSupportFunctions supportFunctions = ((ISAPIApplicationHost) appHost).SupportFunctions; if (supportFunctions != null) { _functions = Misc.CreateLocalSupportFunctions(supportFunctions); } } this._appId = HttpRuntime.AppDomainAppIdInternal; this._appVirtualPath = HttpRuntime.AppDomainAppVirtualPathObject; this._appPhysicalPath = HttpRuntime.AppDomainAppPathInternal; this._appHost = appHost; this._configMapPath = configMapPathFactory.Create(this._appVirtualPath.VirtualPathString, this._appPhysicalPath); HttpConfigurationSystem.EnsureInit(this._configMapPath, true, false); this._configMapPath2 = this._configMapPath as IConfigMapPath2; this._initiateShutdownWorkItemCallback = new WaitCallback(this.InitiateShutdownWorkItemCallback); if (this._appManager != null) { this._appManager.HostingEnvironmentActivated(CacheMemorySizePressure.EffectiveProcessMemoryLimit); } if (this._appHost == null) { this._appHost = new SimpleApplicationHost(this._appVirtualPath, this._appPhysicalPath); } else { this._externalAppHost = true; } this._configToken = this._appHost.GetConfigToken(); this._mapPathBasedVirtualPathProvider = new MapPathBasedVirtualPathProvider(); this._virtualPathProvider = this._mapPathBasedVirtualPathProvider; HttpRuntime.InitializeHostingFeatures(hostingFlags, policyLevel, appDomainCreationException); if (!BuildManagerHost.InClientBuildManager) { this.StartMonitoringForIdleTimeout(); } this.EnforceAppDomainLimit(); this.GetApplicationIdentity(); if (!HttpRuntime.HostingInitFailed) { try { BuildManager.CallPreStartInitMethods(); if ((hostingFlags & HostingEnvironmentFlags.DontCallAppInitialize) == HostingEnvironmentFlags.Default) { BuildManager.CallAppInitializeMethod(); } } catch (Exception exception) { HttpRuntime.InitializationException = exception; if ((hostingFlags & HostingEnvironmentFlags.ThrowHostingInitErrors) != HostingEnvironmentFlags.Default) { throw; } } } }
// New for Dev10. // creates a new AppDomain, preloads and calls user code in it internal void PreloadApplicationIfRequired( string appId, IApplicationHost appHostParameter, HostingEnvironmentParameters hostingParameters, LockableAppDomainContext ac) { // NOTE1: Must never be called under lock (_appManager) // NOTE2: Must always be called under lock (ac) // We only need to preload if auto start is enabled and we have not already preloaded (i.e. HostingEnvironment doesn't exist) if (_preloadUtil == null || ac.PreloadContext == null || ac.HostEnv != null) { return; } // Get and verify the preload parameters string preloadObjTypeName; string[] paramsForStartupObj; bool stillEnabled; GetApplicationPreloadInfoWithAssert(ac.PreloadContext, out stillEnabled, out preloadObjTypeName, out paramsForStartupObj); // Dev10: 782385 ASP.NET autostart implementation should be tolerant of empty string for the provider type if (!stillEnabled || String.IsNullOrEmpty(preloadObjTypeName)) { return; } // Ready to load the App Domain if (_preloadingThrottle != null) { // Throttle the number of simultaneously created appdomains _preloadingThrottle.WaitOne(); } try { // Create the app-host and start a new App Domain IApplicationHost appHost = (appHostParameter == null) ? CreateAppHost(appId, null) : appHostParameter; // call app manager to create the PreloadHost PreloadHost preloadHostObj = (PreloadHost)_appManager.CreateObjectInternal( appId, typeof(PreloadHost), appHost, true /*failIfExists*/, hostingParameters); // Dev10 858421: File sharing violations on config files cause unnecessary process shutdown in autostart mode // // There are race conditions between whoever modifies the config files // and the application config system that reads from the config files // These file sharing violation lead to random application initialization failures // Service auto-start mode is more vulnerable to these sharing violations because // it starts a new app domain as soon as the file change notification is received // and when an error occurs IIS recycles the whole app pool rather than a particular app // // In most cases that we see in stress the inner most exception is System.IO.IOException // so if we see this exception we will give it another try before // reporting the errors to IIS and recycling the process // // Check for I/O exceptions during initialization and retry one time Exception appInitEx = preloadHostObj.InitializationException; if (GetInnerMostException(appInitEx) is IOException) { try { // prevent ApplicationManager.HostingEnvironmentShutdownInitiated from attempting to preload again ac.RetryingPreload = true; // shutdown old hosting environment ac.HostEnv.InitiateShutdownInternal(); } finally { ac.RetryingPreload = false; } // Create the app-host and start a new App Domain appHost = (appHostParameter == null) ? CreateAppHost(appId, null) : appHostParameter; // call app manager to create the PreloadHost preloadHostObj = (PreloadHost)_appManager.CreateObjectInternal( appId, typeof(PreloadHost), appHost, true /*failIfExists*/, hostingParameters); appInitEx = preloadHostObj.InitializationException; } // Check again for initialization exception and tell IIS to recycle the process if (appInitEx != null) { ReportApplicationPreloadFailureWithAssert( ac.PreloadContext, HResults.E_FAIL, Misc.FormatExceptionMessage( appInitEx, new string[] { SR.GetString(SR.Failure_Preload_Application_Initialization)} )); // we must throw if preload fails because we cannot allow the normal // startup path to continue and attempt to create a HostingEnvironment throw appInitEx; } // Call preload code in the App Domain try { preloadHostObj.CreateIProcessHostPreloadClientInstanceAndCallPreload(preloadObjTypeName, paramsForStartupObj); } catch (Exception e) { // report errors ReportApplicationPreloadFailureWithAssert( ac.PreloadContext, HResults.E_FAIL, Misc.FormatExceptionMessage( e, new string[] { SR.GetString(SR.Failure_Calling_Preload_Provider)} ).ToString()); throw; } } finally { if (_preloadingThrottle != null) { _preloadingThrottle.Release(); } } }
internal IRegisteredObject CreateObjectWithDefaultAppHostAndAppId(string physicalPath, VirtualPath virtualPath, Type type, bool failIfExists, HostingEnvironmentParameters hostingParameters, out string appId) { IApplicationHost host; if (physicalPath == null) { HttpRuntime.ForceStaticInit(); ISAPIApplicationHost host2 = new ISAPIApplicationHost(virtualPath.VirtualPathString, null, true, null, hostingParameters.IISExpressVersion); host = host2; appId = host2.AppId; virtualPath = VirtualPath.Create(host.GetVirtualPath()); physicalPath = System.Web.Util.FileUtil.FixUpPhysicalDirectory(host.GetPhysicalPath()); } else { appId = this.CreateSimpleAppID(virtualPath, physicalPath, null); host = new SimpleApplicationHost(virtualPath, physicalPath); } string precompilationTargetPhysicalDirectory = hostingParameters.PrecompilationTargetPhysicalDirectory; if (precompilationTargetPhysicalDirectory != null) { BuildManager.VerifyUnrelatedSourceAndDest(physicalPath, precompilationTargetPhysicalDirectory); if ((hostingParameters.ClientBuildManagerParameter != null) && ((hostingParameters.ClientBuildManagerParameter.PrecompilationFlags & PrecompilationFlags.Updatable) == PrecompilationFlags.Default)) { appId = appId + "_precompile"; } else { appId = appId + "_precompile_u"; } } return this.CreateObjectInternal(appId, type, host, failIfExists, hostingParameters); }
// // IAppDomainProtocolManager // // starts app domain protocol handler on demand (called by process protocol handler public void StartAppDomainProtocolListenerChannel(String appId, String protocolId, IListenerChannelCallback listenerChannelCallback) { try { if (appId == null) throw new ArgumentNullException("appId"); if (protocolId == null) throw new ArgumentNullException("protocolId"); ISAPIApplicationHost appHost = CreateAppHost(appId, null); // get app domaoin protocol handler type from config Type handlerType = GetAppDomainProtocolHandlerType(protocolId); AppDomainProtocolHandler handler = null; LockableAppDomainContext ac = _appManager.GetLockableAppDomainContext(appId); lock (ac) { HostingEnvironmentParameters hostingParameters = new HostingEnvironmentParameters(); hostingParameters.HostingFlags = HostingEnvironmentFlags.ThrowHostingInitErrors; PreloadApplicationIfRequired(appId, appHost, hostingParameters, ac); // call app manager to create the handler handler = (AppDomainProtocolHandler)_appManager.CreateObjectInternal( appId, handlerType, appHost, false /*failIfExists*/, hostingParameters); // create a shim object that we can use for proxy unwrapping ListenerAdapterDispatchShim shim = (ListenerAdapterDispatchShim) _appManager.CreateObjectInternal( appId, typeof(ListenerAdapterDispatchShim), appHost, false /*failIfExists*/, hostingParameters); if (null != shim) { shim.StartListenerChannel(handler, listenerChannelCallback); // remove the shim ((IRegisteredObject)shim).Stop(true); } else { throw new HttpException(SR.GetString(SR.Failure_Create_Listener_Shim)); } } } catch (Exception e) { using (new ProcessImpersonationContext()) { Misc.ReportUnhandledException(e, new string[] { SR.GetString(SR.Failure_Start_AppDomain_Listener)} ); } throw; } }
internal void PreloadApplicationIfRequired(string appId, IApplicationHost appHostParameter, HostingEnvironmentParameters hostingParameters, LockableAppDomainContext ac) { if (((this._preloadUtil != null) && (ac.PreloadContext != null)) && (ac.HostEnv == null)) { string str; string[] strArray; bool flag; this.GetApplicationPreloadInfoWithAssert(ac.PreloadContext, out flag, out str, out strArray); if (flag && !string.IsNullOrEmpty(str)) { if (this._preloadingThrottle != null) { this._preloadingThrottle.WaitOne(); } try { IApplicationHost appHost = (appHostParameter == null) ? this.CreateAppHost(appId, null) : appHostParameter; PreloadHost host2 = (PreloadHost)this._appManager.CreateObjectInternal(appId, typeof(PreloadHost), appHost, true, hostingParameters); Exception initializationException = host2.InitializationException; if (GetInnerMostException(initializationException) is IOException) { try { ac.RetryingPreload = true; ac.HostEnv.InitiateShutdownInternal(); } finally { ac.RetryingPreload = false; } appHost = (appHostParameter == null) ? this.CreateAppHost(appId, null) : appHostParameter; host2 = (PreloadHost)this._appManager.CreateObjectInternal(appId, typeof(PreloadHost), appHost, true, hostingParameters); initializationException = host2.InitializationException; } if (initializationException != null) { this.ReportApplicationPreloadFailureWithAssert(ac.PreloadContext, -2147467259, Misc.FormatExceptionMessage(initializationException, new string[] { System.Web.SR.GetString("Failure_Preload_Application_Initialization") })); throw initializationException; } try { host2.CreateIProcessHostPreloadClientInstanceAndCallPreload(str, strArray); } catch (Exception exception2) { this.ReportApplicationPreloadFailureWithAssert(ac.PreloadContext, -2147467259, Misc.FormatExceptionMessage(exception2, new string[] { System.Web.SR.GetString("Failure_Calling_Preload_Provider") }).ToString()); throw; } } finally { if (this._preloadingThrottle != null) { this._preloadingThrottle.Release(); } } } } }