internal CacheManager(ApplicationManager appManager, long privateBytesLimit) {
#if PERF
            SafeNativeMethods.OutputDebugString(String.Format("Creating CacheManager with PrivateBytesLimit = {0:N}\n", privateBytesLimit));
#endif
            // don't create timer if there's no memory limit
            if (privateBytesLimit <= 0) {
                return;
            }

            _appManager = appManager;
            _limit = privateBytesLimit;

            _pid = (uint) SafeNativeMethods.GetCurrentProcessId();
            
            // the initial expected maximum increase in private bytes is 2MB per second per CPU
            _minMaxDelta = 2 * MEGABYTE * SystemInfo.GetNumProcessCPUs();
            AdjustMaxDeltaAndPressureMarks(_minMaxDelta);

            _samples = new long[SAMPLE_COUNT];
            _sampleTimes = new DateTime[SAMPLE_COUNT];
            _useGetProcessMemoryInfo = (VersionInfo.ExeName == "w3wp");
            _deltaSamples = new long[DELTA_SAMPLE_COUNT];
            
            // start timer with initial poll interval
            _timer = new Timer(new TimerCallback(this.PBytesMonitorThread), null, _currentPollInterval, _currentPollInterval);
        }
Exemple #2
0
        public Server(int port, string virtualPath, string physicalPath) {
            _port = port;
            _virtualPath = virtualPath;
            _physicalPath = physicalPath.EndsWith("\\", StringComparison.Ordinal) ? physicalPath : physicalPath + "\\";

            _onSocketAccept = new WaitCallback(OnSocketAccept);
            _onStart = new WaitCallback(OnStart);

            _appManager = ApplicationManager.GetApplicationManager();
        }
		public ClientBuildManager (string appVirtualDir, string appPhysicalSourceDir)
		{
			if (appVirtualDir == null || appVirtualDir == "")
				throw new ArgumentNullException ("appVirtualDir");
			if (appPhysicalSourceDir == null || appPhysicalSourceDir == "")
				throw new ArgumentNullException ("appPhysicalSourceDir");

			virt_dir = appVirtualDir; // TODO: adjust vpath (it allows 'blah' that turns into '/blah', '////blah', '\\blah'...
			phys_src_dir = appPhysicalSourceDir;
			manager = ApplicationManager.GetApplicationManager ();
		}
Exemple #4
0
        public Server(int port, string virtualPath, string physicalPath)
        {
            _port = port;
            _virtualPath = virtualPath;
            _physicalPath = physicalPath.EndsWith("\\", StringComparison.Ordinal) ? physicalPath : physicalPath + "\\";
            _registeredContent = new Dictionary<string, string>();

            _socketAcceptCallback = new WaitCallback(OnSocketAccept);
            _startCallback = new WaitCallback(OnStart);

            _appManager = ApplicationManager.GetApplicationManager();
        }
Exemple #5
0
 public Server(IPAddress endPoint, string virtualDir, string physicalDir, int port)
 {
     _endPoint = endPoint;
     _virtualDir = virtualDir;
     _physicalDir = physicalDir;
     if (!_physicalDir.EndsWith("\\"))
         _physicalDir += "\\";
     _port = port;
     _appId = Guid.NewGuid().ToString(); //generate a new application id
     _appManager = ApplicationManager.GetApplicationManager();
     PrepareServerVariables();
     ConfigureResponses();
 }
    /// <summary>
    /// Initializes a new instance of the <see cref="TestApplicationManager"/> class.
    /// </summary>
    /// <param name="applicationManager">The application manager.</param>
    /// <param name="testApplicationType">The test application type.</param>
    public TestApplicationManager(ApplicationManager applicationManager, Type testApplicationType)
    {
      if (applicationManager == null)
      {
        throw new ArgumentNullException("applicationManager");
      }

      if (testApplicationType == null)
      {
        throw new ArgumentNullException("testApplicationType");
      }

      if (!typeof(TestApplication).IsAssignableFrom(testApplicationType))
      {
        throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Only applications derived from '{0}' are supported.", typeof(TestApplication).AssemblyQualifiedName));
      }

      this.applicationManager = applicationManager;
      this.testApplicationType = testApplicationType;
    }
 internal CacheManager(ApplicationManager appManager, long privateBytesLimit)
 {
     this._lastTrimPercent = 10;
     this._inducedGCMinInterval = 0x2faf080L;
     this._inducedGCFinishTime = DateTime.MinValue;
     this._currentPollInterval = 0x7530;
     this._timerSuspendTime = DateTime.MinValue;
     this._timerLock = new object();
     if (privateBytesLimit > 0L)
     {
         this._appManager = appManager;
         this._limit = privateBytesLimit;
         this._pid = (uint) SafeNativeMethods.GetCurrentProcessId();
         this._minMaxDelta = 0x200000L * SystemInfo.GetNumProcessCPUs();
         this.AdjustMaxDeltaAndPressureMarks(this._minMaxDelta);
         this._samples = new long[2];
         this._sampleTimes = new DateTime[2];
         this._useGetProcessMemoryInfo = VersionInfo.ExeName == "w3wp";
         this._deltaSamples = new long[10];
         this._timer = new Timer(new TimerCallback(this.PBytesMonitorThread), null, this._currentPollInterval, this._currentPollInterval);
     }
 }
Exemple #8
0
 public Server(int port, string virtualPath, string physicalPath, bool requireAuthentication,
               bool disableDirectoryListing)
 {
     _ipAddress = IPAddress.Loopback;
     _requireAuthentication = requireAuthentication;
     _disableDirectoryListing = disableDirectoryListing;
     _lockObject = new object();
     _port = port;
     _virtualPath = virtualPath;
     _physicalPath = Path.GetFullPath(physicalPath);
     _physicalPath = _physicalPath.EndsWith("\\", StringComparison.Ordinal)
                         ? _physicalPath
                         : _physicalPath + "\\";
     _appManager = ApplicationManager.GetApplicationManager();
     ObtainProcessToken();
 }
 public AppManagerAppDomainFactory() {
     _appManager = ApplicationManager.GetApplicationManager();
     _appManager.Open();
 }
Exemple #10
0
		void RunInternal (ApplicationManager appMan)
		{
			ITestCase test = Activator.CreateInstance (TestType) as ITestCase;
			var runItems = new List <TestRunItem> ();			
			if (!test.SetUp (runItems)) {
				Success = false;
				FailureDetails = "Test aborted in setup phase.";
				return;
			}

			if (runItems.Count == 0) {
				Success = false;
				FailureDetails = "No test run items returned by the test case.";
				return;
			}
			
			Response response, previousResponse = null;
			TestRunner runner;
			string[] formValues;
			
			try {
				Console.Write ('[');
				foreach (var tri in runItems) {
					if (tri == null)
						continue;

					runner = null;
					response = null;
					try {
						runner = appMan.CreateObject (Info.Name, typeof (TestRunner), test.VirtualPath, test.PhysicalPath, true) as TestRunner;
						if (runner == null) {
							Success = false;
							throw new InvalidOperationException ("runner must not be null.");
						}
						
						if (tri.PostValues != null && previousResponse != null)
							formValues = ExtractFormAndHiddenControls (previousResponse);
						else
							formValues = null;
						
						response = runner.Run (tri.Url, tri.PathInfo, tri.PostValues, formValues);
						if (tri.Callback == null)
							continue;

						tri.TestRunData = runner.TestRunData;
						tri.StatusCode = runner.StatusCode;
						tri.Redirected = runner.Redirected;
						tri.RedirectLocation = runner.RedirectLocation;	

						if (tri.Callback != null)
							tri.Callback (response.Body, tri);
						
						Console.Write ('.');
					} catch (Exception) {
						FailedUrl = tri.Url;
						FailedUrlDescription = tri.UrlDescription;

						if (tri.Callback != null) {
							MethodInfo mi = tri.Callback.Method;
							FailedUrlCallbackName = FormatMethodName (mi);
						}
						Console.Write ('F');
						throw;
					} finally {
						if (runner != null) {
							runner.Stop (true);
							AppDomain.Unload (runner.Domain);
						}
						runner = null;
						previousResponse = response;
					}
				}
			} catch (AssertionException ex) {
				throw new TestCaseFailureException ("Assertion failed.", ex.Message, ex);
			} finally {
				Console.Write (']');
			}
		}
Exemple #11
0
		public void Run (ApplicationManager appMan)
		{
			try {
				Success = true;
				RunInternal (appMan);
			} catch (TestCaseFailureException ex) {
				Exception = ex;
				Success = false;
			} catch (Exception ex) {
				FailureDetails = String.Format ("Test failed with exception of type '{0}':{1}{2}",
								ex.GetType (), Environment.NewLine, ex.ToString ());
				Success = false;
			}
		}
        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;
                    }
                }
            }
        }
        ///<summary>
        ///</summary>
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="requireAuthentication"></param>
        ///<param name="disableDirectoryListing"></param>
        public Server(int port, string virtualPath, string physicalPath, bool requireAuthentication,
                      bool disableDirectoryListing)
        {
            
            _ipAddress = IPAddress.Loopback;
            _requireAuthentication = requireAuthentication;
            _disableDirectoryListing = disableDirectoryListing;
            _lockObject = new object();
            _port = port;
            _virtualPath = virtualPath;

            _physicalPath = PreparePhysicalPath(physicalPath);

            ProcessConfiguration();

            _applicationManager = ApplicationManager.GetApplicationManager();

            string uniqueAppString = string.Concat(_virtualPath, _physicalPath, ":", _port.ToString()).ToLowerInvariant();

            _appId = (uniqueAppString.GetHashCode()).ToString("x", CultureInfo.InvariantCulture);

            ObtainProcessToken();
        }
Exemple #14
0
		public static int Main (string [] args)
		{
			// Load the configuration file stored in the
			// executable's resources.
			configmanager = new ConfigurationManager (
				typeof (Server).Assembly,
				"ConfigurationManager.xml");
			
			configmanager.LoadCommandLineArgs (args);
			
			// Show the help and exit.
			if ((bool) configmanager ["help"] ||
				(bool) configmanager ["?"]) {
				ShowHelp ();
				return 0;
			}
			
			// Show the version and exit.
			if ((bool) configmanager ["version"]) {
				ShowVersion ();
				return 0;
			}
			
			try {
				string config_file = (string)
					configmanager ["configfile"];
				if (config_file != null)
					configmanager.LoadXmlConfig (
						config_file);
			} catch (ApplicationException e) {
				Console.WriteLine (e.Message);
				return 1;
			} catch (System.Xml.XmlException e) {
				Console.WriteLine (
					"Error reading XML configuration: {0}",
					e.Message);
				return 1;
			}
			
			try {
				string log_level = (string)
					configmanager ["loglevels"];
				
				if (log_level != null)
					Logger.Level = (LogLevel)
						Enum.Parse (typeof (LogLevel),
							log_level);
			} catch {
				Console.WriteLine ("Failed to parse log levels.");
				Console.WriteLine ("Using default levels: {0}",
					Logger.Level);
			}
			
			try {
				string log_file = (string)
					configmanager ["logfile"];
				
				if (log_file != null)
					Logger.Open (log_file);
			} catch (Exception e) {
				Console.WriteLine ("Error opening log file: {0}",
					e.Message);
				Console.WriteLine ("Events will not be logged.");
			}
			
			Logger.WriteToConsole = (bool) configmanager ["printlog"];

			// Send the trace to the console.
			Trace.Listeners.Add (
				new TextWriterTraceListener (Console.Out));
			Console.WriteLine (
				Assembly.GetExecutingAssembly ().GetName ().Name);
			
			
			// Create the socket.
			Socket socket;
			
			// Socket strings are in the format
			// "type[:ARG1[:ARG2[:...]]]".
			string socket_type = configmanager ["socket"] as string;
			if (socket_type == null)
				socket_type = "pipe";
			
			string [] socket_parts = socket_type.Split (
				new char [] {':'}, 3);
			
			switch (socket_parts [0].ToLower ()) {
			case "pipe":
				try {
					socket = SocketFactory.CreatePipeSocket (
						IntPtr.Zero);
				} catch (System.Net.Sockets.SocketException){
					Console.WriteLine (
						"Error: Pipe socket is not bound.");
					return 1;
				}
				break;
			
			// The FILE sockets is of the format
			// "file[:PATH]".
			case "unix":
			case "file":
				if (socket_parts.Length == 2)
					configmanager ["filename"] =
						socket_parts [1];
				
				string path = (string) configmanager ["filename"];
				
				try {
					socket = SocketFactory.CreateUnixSocket (
						path);
				} catch (System.Net.Sockets.SocketException e){
					Console.WriteLine (
						"Error creating the socket: {0}",
						e.Message);
					return 1;
				}
				
				Console.WriteLine ("Listening on file: {0}",
					path);
				break;
			
			// The TCP socket is of the format
			// "tcp[[:ADDRESS]:PORT]".
			case "tcp":
				if (socket_parts.Length > 1)
					configmanager ["port"] = socket_parts [
						socket_parts.Length - 1];
				
				if (socket_parts.Length == 3)
					configmanager ["address"] =
						socket_parts [1];
				
				ushort port;
				try {
					port = (ushort) configmanager ["port"];
				} catch (ApplicationException e) {
					Console.WriteLine (e.Message);
					return 1;
				}
				
				string address_str =
					(string) configmanager ["address"];
				IPAddress address;
				
				try {
					address = IPAddress.Parse (address_str);
				} catch {
					Console.WriteLine (
						"Error in argument \"address\". \"{0}\" cannot be converted to an IP address.",
						address_str);
					return 1;
				}
				
				try {
					socket = SocketFactory.CreateTcpSocket (
						address, port);
				} catch (System.Net.Sockets.SocketException e){
					Console.WriteLine (
						"Error creating the socket: {0}",
						e.Message);
					return 1;
				}
				
				Console.WriteLine ("Listening on port: {0}",
					address_str);
				Console.WriteLine ("Listening on address: {0}",
					port);
				break;
				
			default:
				Console.WriteLine (
					"Error in argument \"socket\". \"{0}\" is not a supported type. Use \"pipe\", \"tcp\" or \"unix\".",
					socket_parts [0]);
				return 1;
			}
			
			string root_dir = configmanager ["root"] as string;
			if (root_dir != null && root_dir.Length != 0) {
				try {
					Environment.CurrentDirectory = root_dir;
				} catch (Exception e) {
					Console.WriteLine ("Error: {0}",
						e.Message);
					return 1;
				}
			}
			
			root_dir = Environment.CurrentDirectory;
			bool auto_map = (bool) configmanager ["automappaths"];
			appmanager = new ApplicationManager (
				typeof (ApplicationHost), auto_map, false);
			appmanager.Verbose = (bool) configmanager ["verbose"];
			
			string applications = (string)
				configmanager ["applications"];
			string app_config_file;
			string app_config_dir;
			
			try {
				app_config_file = (string)
					configmanager ["appconfigfile"];
				app_config_dir = (string)
					configmanager ["appconfigdir"];
			} catch (ApplicationException e) {
				Console.WriteLine (e.Message);
				return 1;
			}
			
			if (applications != null)
				appmanager.AddApplicationsFromCommandLine (
					applications);
			
			if (app_config_file != null)
				appmanager.AddApplicationsFromConfigFile (
					app_config_file);
			
			if (app_config_dir != null)
				appmanager.AddApplicationsFromConfigDirectory (
					app_config_dir);

			if (applications == null && app_config_dir == null &&
				app_config_file == null && !auto_map) {
				Console.WriteLine (
					"There are no applications defined, and path mapping is disabled.");
				Console.WriteLine (
					"Define an application using /applications, /appconfigfile, /appconfigdir");
				Console.WriteLine (
					"or by enabling application mapping with /automappaths=True.");
				return 1;
			}
			
			Console.WriteLine ("Root directory: {0}", root_dir);
			Mono.FastCgi.Server server = new Mono.FastCgi.Server (
				socket);
			
			server.SetResponder (typeof (Responder));
			
			server.MaxConnections = (ushort)
				configmanager ["maxconns"];
			server.MaxRequests = (ushort)
				configmanager ["maxreqs"];
			server.MultiplexConnections = (bool)
				configmanager ["multiplex"];
			
			Console.WriteLine ("Max connections: {0}",
				server.MaxConnections);
			Console.WriteLine ("Max requests: {0}",
				server.MaxRequests);
			Console.WriteLine ("Multiplex connections: {0}",
				server.MultiplexConnections);
			
			bool stopable = (bool) configmanager ["stopable"];
			if (!stopable)
				Console.WriteLine (
					"Use /stopable=True to enable stopping from the console.");
			
			server.Start (stopable);
			
			configmanager = null;
			
			if (stopable) {
				Console.WriteLine (
					"Hit Return to stop the server.");
				Console.ReadLine ();
				server.Stop ();
			}
			
			return 0;
		}
Exemple #15
0
        ///<summary>
        ///</summary>
        ///<param name="port"></param>
        ///<param name="virtualPath"></param>
        ///<param name="physicalPath"></param>
        ///<param name="requireAuthentication"></param>
        ///<param name="disableDirectoryListing"></param>
        public Server(int port, string virtualPath, string physicalPath, bool requireAuthentication,
                      bool disableDirectoryListing)
        {
            try
            {
                Assembly.ReflectionOnlyLoad("Common.Logging");
                _useLogger = true;
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch
            // ReSharper restore EmptyGeneralCatchClause
            {
            }
            _ipAddress = IPAddress.Loopback;
            _requireAuthentication = requireAuthentication;
            _disableDirectoryListing = disableDirectoryListing;
            _lockObject = new object();
            _port = port;
            _virtualPath = virtualPath;
            _physicalPath = Path.GetFullPath(physicalPath);
            _physicalPath = _physicalPath.EndsWith("\\", StringComparison.Ordinal)
                                ? _physicalPath
                                : _physicalPath + "\\";
            ProcessConfiguration();

            ApplicationManager = ApplicationManager.GetApplicationManager();
            string uniqueAppString = string.Concat(virtualPath, physicalPath,":",_port.ToString()).ToLowerInvariant();
            _appId = (uniqueAppString.GetHashCode()).ToString("x", CultureInfo.InvariantCulture);
            ObtainProcessToken();
        }
Exemple #16
0
        public Server(int port, string virtualPath, string physicalPath, bool requireAuthentication,
            bool disableDirectoryListing)
        {
            try
            {
                Assembly.ReflectionOnlyLoad("Common.Logging");
                _useLogger = true;
            }
                // ReSharper disable EmptyGeneralCatchClause
            catch
                // ReSharper restore EmptyGeneralCatchClause
            {
            }
            _ipAddress = IPAddress.Loopback;
            _requireAuthentication = requireAuthentication;
            _disableDirectoryListing = true;
            _lockObject = new object();
            _port = port;
            _virtualPath = virtualPath;
            _physicalPath = Path.GetFullPath(physicalPath);
            _physicalPath = _physicalPath.EndsWith("\\", StringComparison.Ordinal)
                                ? _physicalPath
                                : _physicalPath + "\\";
            ProcessConfiguration();

            _appManager = ApplicationManager.GetApplicationManager();
            ObtainProcessToken();
        }
        //
        // 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);
        }
 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;
             }
         }
     }
 }
        private ProcessHost(IProcessHostSupportFunctions functions) {
            try {
                // remember support functions
                _functions = functions;

                // pass them along to the HostingEnvironment in the default domain
                HostingEnvironment.SupportFunctions = functions;

                // create singleton app manager
                _appManager = ApplicationManager.GetApplicationManager();

                // For M3 we get the throttling limit from the registry.
                // Dev10\Beta1 work item 543420 is to investigate whether we need to get rid of the throttling
                int maxPreloadConcurrency = (int)Misc.GetAspNetRegValue(null, "MaxPreloadConcurrency", 0);
                if (maxPreloadConcurrency > 0) {
                    _preloadingThrottle = new System.Threading.Semaphore(maxPreloadConcurrency, maxPreloadConcurrency);
                }


            }
            catch (Exception e) {
                using (new ProcessImpersonationContext()) {
                    Misc.ReportUnhandledException(e, new string[]
                                                  { SR.GetString(SR.Cant_Create_Process_Host)});
                    Debug.Trace("internal", "ProcessHost::ctor failed with " + e.GetType().FullName + ": " + e.Message + "\r\n" + e.StackTrace);
                }
                throw;
            }
        }
 public static ApplicationManager GetApplicationManager()
 {
     if (_theAppManager == null)
     {
         lock (_applicationManagerStaticLock)
         {
             if (_theAppManager == null)
             {
                 if (HostingEnvironment.IsHosted)
                 {
                     _theAppManager = HostingEnvironment.GetApplicationManager();
                 }
                 if (_theAppManager == null)
                 {
                     _theAppManager = new ApplicationManager();
                 }
             }
         }
     }
     return _theAppManager;
 }