private static void AddAllAssembliesFromAppDomainBinDirectory(
                CompilationConfiguration result, XmlNode child)
            {
                // Get the path to the bin directory
                string binPath = HttpRuntime.BinDirectoryInternal;

                FileInfo[] binDlls;

                if (!FileUtil.DirectoryExists(binPath))
                {
                    // This is expected to fail if there is no 'bin' dir
                    Debug.Trace("Template", "Failed to access bin dir \"" + binPath + "\"");
                }
                else
                {
                    DirectoryInfo binPathDirectory = new DirectoryInfo(binPath);
                    // Get a list of all the DLL's in the bin directory
                    binDlls = binPathDirectory.GetFiles("*.dll");

                    string configFile = ConfigurationException.GetXmlNodeFilename(child);

                    for (int i = 0; i < binDlls.Length; i++)
                    {
                        string assemblyName = Util.GetAssemblyNameFromFileName(binDlls[i].Name);

                        // Remember the config file location info, in case an error
                        // occurs later when we try to load the assembly (ASURT 72183)
                        int configFileLine = ConfigurationException.GetXmlNodeLineNumber(child);
                        result._assemblies[assemblyName] = new object[]
                        { configFile, configFileLine, true /*starDirective*/ };
                    }
                }
            }
Beispiel #2
0
        internal /*public*/ static void BatchCompile(string virtualDir, HttpContext context)
        {
            string prevConfigPath = context.ConfigPath;

            try {
                try {
                    // Set the config path to the virtual path that we're batching
                    Debug.Trace("Batching", "Setting ConfigPath to " + virtualDir);
                    context.ConfigPath = virtualDir;

                    BatchCompileInternal(virtualDir, context);
                }
                catch (Exception e) {
                    // Save the exception
                    _batchErrors[virtualDir] = e;
                    throw;
                }
                finally {
                    // Restore the config path to its previous value
                    Debug.Trace("Batching", "Restoring ConfigPath to " + prevConfigPath);
                    context.ConfigPath = prevConfigPath;
                }
            }
            catch { throw; } // Prevent Exception Filter Security Issue (ASURT 122825)
        }
        private void CreateHost()
        {
            Debug.Trace("CBM", "CreateHost");
            Debug.Assert(_host == null);

            Debug.Assert(!_hostCreationPending, "CreateHost: creation already pending");

            _hostCreationPending = true;

            // Use a local to avoid having a partially created _host
            BuildManagerHost host = null;

            try {
                string           appId;
                IApplicationHost appHost;

                ApplicationManager appManager = ApplicationManager.GetApplicationManager();

                host = (BuildManagerHost)appManager.CreateObjectWithDefaultAppHostAndAppId(
                    _physicalPath, _virtualPath,
                    typeof(BuildManagerHost), false /*failIfExists*/,
                    _hostingParameters, out appId, out appHost);

                // host appdomain cannot be unloaded during creation.
                host.AddPendingCall();

                host.Configure(this);

                _host    = host;
                _appId   = appId;
                _appHost = appHost;

                _hostCreationException = _host.InitializationException;
            }
            catch (Exception e) {
                // If an exception happens, keep track of it
                _hostCreationException = e;

                // Even though the host initialization failed, keep track of it so subsequent
                // request will see the error
                _host = host;
            }
            finally {
                _hostCreationPending = false;

                if (host != null)
                {
                    // Notify the client that the host is ready
                    if (AppDomainStarted != null)
                    {
                        AppDomainStarted(this, EventArgs.Empty);
                    }

                    // The host can be unloaded safely now.
                    host.RemovePendingCall();
                }
            }

            Debug.Trace("CBM", "CreateHost LEAVE");
        }
Beispiel #4
0
        internal static PreservedAssemblyEntry GetPreservedAssemblyEntry(HttpContext context,
                                                                         string virtualPath, bool fApplicationFile)
        {
            Debug.Trace("PreservedAssemblyEntry", "Checking for " + virtualPath);

            EnsureFirstTimeInit(context);

            string baseVirtualDir = UrlPath.GetDirectory(virtualPath);

            // No batching for global.asax
            if (!fApplicationFile)
            {
                BatchCompileDirectory(context, baseVirtualDir);
            }

            PreservedAssemblyEntry entry = new PreservedAssemblyEntry(context,
                                                                      virtualPath, fApplicationFile);

            // Try to load the entry.  It must exist, and be up to date
            if (!entry.LoadDataFromFile(fApplicationFile))
            {
                return(null);
            }

            return(entry);
        }
Beispiel #5
0
        /*
         * Delete all temporary files from the codegen directory (e.g. source files, ...)
         */
        private static void RemoveOldTempFiles()
        {
            Debug.Trace("PreservedAssemblyEntry", "Deleting old temporary files from " + HttpRuntime.CodegenDirInternal);

            string codegen = HttpRuntime.CodegenDirInternal + "\\";

            UnsafeNativeMethods.WIN32_FIND_DATA wfd;
            IntPtr hFindFile = UnsafeNativeMethods.FindFirstFile(codegen + "*.*", out wfd);

            // No files: do nothing
            if (hFindFile == new IntPtr(-1))
            {
                return;
            }

            try {
                // Go through all the files in the codegen dir. We use the Win32 native API's
                // directly for perf and memory usage reason (ASURT 97791)
                for (bool more = true; more; more = UnsafeNativeMethods.FindNextFile(hFindFile, out wfd))
                {
                    // Skip directories
                    if ((wfd.dwFileAttributes & UnsafeNativeMethods.FILE_ATTRIBUTE_DIRECTORY) != 0)
                    {
                        continue;
                    }

                    // If it has a known extension, skip it
                    string ext = Path.GetExtension(wfd.cFileName);
                    if (ext == ".dll" || ext == ".pdb" || ext == ".web" || ext == ".xml")
                    {
                        continue;
                    }

                    // Don't delete the temp file if it's named after a dll that's still around
                    // since it could still be useful for debugging.
                    // Note that we can't use GetFileNameWithoutExtension here because
                    // some of the files are named 5hvoxl6v.0.cs, and it would return
                    // 5hvoxl6v.0 instead of just 5hvoxl6v
                    int periodIndex = wfd.cFileName.IndexOf('.');
                    if (periodIndex > 0)
                    {
                        string baseName = wfd.cFileName.Substring(0, periodIndex);

                        if (FileUtil.FileExists(codegen + baseName + ".dll"))
                        {
                            continue;
                        }
                    }

                    try {
                        File.Delete(codegen + wfd.cFileName);
                    }
                    catch { } // Ignore all exceptions
                }
            }
            finally {
                UnsafeNativeMethods.FindClose(hFindFile);
            }
        }
        public IDictionary GetBrowserDefinitions()
        {
            Debug.Trace("CBM", "GetBrowserDefinitions");

            EnsureHostCreated();

            return(_host.GetBrowserDefinitions());
        }
        /*
         * Returns an array of the virtual paths to all the code directories in the app thru the hosted appdomain
         */

        public string[] GetVirtualCodeDirectories()
        {
            Debug.Trace("CBM", "GetHostedVirtualCodeDirectories");

            EnsureHostCreated();

            return(_host.GetVirtualCodeDirectories());
        }
        /*
         * Makes sure that all the top level files are compiled (code, global.asax, ...)
         */

        public void CompileApplicationDependencies()
        {
            Debug.Trace("CBM", "CompileApplicationDependencies");

            EnsureHostCreated();

            _host.CompileApplicationDependencies();
        }
Beispiel #9
0
        private static void BatchCompileInternal(string virtualDir, HttpContext context)
        {
            string directory = context.Request.MapPath(virtualDir);

            // Prescan all files in the current directory to see inter-file dependencies
            DirectoryInfo       filesDirectory = new DirectoryInfo(directory);
            BatchTemplateParser btp            = new BatchTemplateParser(context);

            AddFileSet(virtualDir, filesDirectory, "*.aspx", btp);
            AddFileSet(virtualDir, filesDirectory, "*.ascx", btp);

            // Based on dependencies, split into phases

            SourceReference[][] sources = BatchDependencyWalker.Split(btp.GetSourceReferences());
            btp = null;

            // Tell the server that we're still running to make sure it doesn't kill us (ASURT 96452)
            context.SendEmptyResponse();

#if DBG
            for (int i = 0; i < sources.Length; i++)
            {
                SourceReference[] bucket = sources[i];
                Debug.Trace("Batching", "");
                Debug.Trace("Batching", "Bucket " + i + " contains " + bucket.Length + " files");

                for (int j = 0; j < bucket.Length; j++)
                {
                    Debug.Trace("Batching", bucket[j].Filename);
                }
            }
#endif

            // Batch compile each phase separately

            for (int i = 0; i < sources.Length; i++)
            {
                SourceReference[] batch = sources[i];
                ArrayList         list  = new ArrayList();

                // cons up the TemplateParserParameters

                for (int j = 0; j < batch.Length; j++)
                {
                    string filename    = batch[j].Filename;
                    string virtualPath = UrlPath.Combine(virtualDir,
                                                         Path.GetFileName(filename));
                    list.Add(new BatchCompilationEntry(virtualPath, filename, context));
                }

                // Now batch compile them

                if (list.Count > 0)
                {
                    BatchCompile(list, context, virtualDir);
                }
            }
        }
        /*
         * Returns the codedom tree and the compiler type/param for a given file.
         */

        public CodeCompileUnit GenerateCodeCompileUnit(
            string virtualPath, out Type codeDomProviderType,
            out CompilerParameters compilerParameters, out IDictionary linePragmasTable)
        {
            Debug.Trace("CBM", "GenerateCodeCompileUnit " + virtualPath);

            return(GenerateCodeCompileUnit(virtualPath, null,
                                           out codeDomProviderType, out compilerParameters, out linePragmasTable));
        }
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)
        {
            Debug.Trace("PageHandlerFactory", "PageHandlerFactory: " + virtualPath);

            // This should never get called in ISAPI mode but currently is in integrated mode
            // Debug.Assert(false);

            return(GetHandlerHelper(context, requestType, VirtualPath.CreateNonRelative(virtualPath), path));
        }
        static bool GetSiteNameFromISAPI()
        {
            Debug.Trace("config_loc", "GetSiteNameFromISAPI()");
            HttpContext context = HttpContext.Current;

            if (context != null)
            {
                string       metabaseAppKey = context.Request.ServerVariables["INSTANCE_META_PATH"];
                const string KEY_LMW3SVC    = "/LM/W3SVC/";
                Debug.Assert(metabaseAppKey.StartsWith(KEY_LMW3SVC));
                string appNumber = metabaseAppKey.Substring(KEY_LMW3SVC.Length - 1);
                //string appServerComment = "/" + appNumber + "/ServerComment";
                Debug.Trace("config_loc", "appNumber:" + appNumber + " INSTANCE_META_PATH:" + metabaseAppKey);

                UnicodeEncoding encoding = new UnicodeEncoding();

                // null-terminate appNumber and convert to byte array
                byte [] byteAppNumber = encoding.GetBytes(appNumber + "\0");

                int     retVal   = 2;
                byte [] outBytes = new byte[64];
                while (retVal == 2)
                {
                    retVal = context.CallISAPI(UnsafeNativeMethods.CallISAPIFunc.GetSiteServerComment,
                                               byteAppNumber, outBytes);
                    if (retVal == 2)
                    {
                        if (outBytes.Length > 1024)   // should never happen
                        {
                            throw new ConfigurationException(HttpRuntime.FormatResourceString(
                                                                 SR.Config_site_name_too_long,
                                                                 metabaseAppKey));
                        }
                        outBytes = new byte[outBytes.Length * 2];
                    }
                }

                // find WCHAR null terminator in byte array
                int i = 0;
                while (i + 1 < outBytes.Length && (outBytes[i] != 0 || outBytes[i + 1] != 0))
                {
                    i += 2;
                }

                // decode up to null terminator
                s_siteName = encoding.GetString(outBytes, 0, i);
                Debug.Trace("config_loc", "i: " + i + " site name:" + s_siteName);

                return(true);
            }
            else
            {
                Debug.Trace("config_loc", "could not query site name.  No Context.");
            }

            return(false); // keep trying to evaluate
        }
        private void OnAppDomainUnloadedCallback(Object unused)
        {
            Debug.Trace("CBM", "OnAppDomainUnloadedCallback");

            // Notify the client that the appdomain is unloaded
            if (AppDomainUnloaded != null)
            {
                AppDomainUnloaded(this, new BuildManagerHostUnloadEventArgs(_reason));
            }
        }
        // Called by BuildManagerHost when the ASP appdomain is unloaded
        internal void OnAppDomainUnloaded(ApplicationShutdownReason reason)
        {
            Debug.Trace("CBM", "OnAppDomainUnloaded " + reason.ToString());

            _reason          = reason;
            _waitForCallBack = false;

            // Don't do anything that can be slow here.  Instead queue in a worker thread
            ThreadPool.QueueUserWorkItem(_onAppDomainUnloadedCallback);
        }
Beispiel #15
0
        protected void AddDependency(VirtualPath virtualPath)
        {
            virtualPath = ResolveVirtualPath(virtualPath);
            Debug.Trace("Template", "Parsed dependency: " + _virtualPath + " depends on " + virtualPath);

            if (_virtualPathDependencies == null)
            {
                _virtualPathDependencies = new CaseInsensitiveStringSet();
            }

            _virtualPathDependencies.Add(virtualPath.VirtualPathString);
        }
        /*
         * Returns an array of the assemblies defined in the bin and assembly reference config section
         */

        public String[] GetTopLevelAssemblyReferences(string virtualPath)
        {
            Debug.Trace("CBM", "GetHostedVirtualCodeDirectories");

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

            EnsureHostCreated();

            return(_host.GetTopLevelAssemblyReferences(VirtualPath.Create(virtualPath)));
        }
        /*
         * Returns the virtual path of the corresponding generated file.
         * Note the filepath needs to be a full path.
         */
        public string GetGeneratedFileVirtualPath(string filePath)
        {
            Debug.Trace("CBM", "GetGeneratedFileVirtualPath " + filePath);

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

            EnsureHostCreated();

            return(_host.GetGeneratedFileVirtualPath(filePath));
        }
        /*
         * Returns the physical path of the generated file corresponding to the virtual directory.
         * Note the virtualPath needs to use this format:
         * "/[appname]/App_WebReferences/{[subDir]/}"
         */
        public string GetGeneratedSourceFile(string virtualPath)
        {
            Debug.Trace("CBM", "GetGeneratedSourceFile " + virtualPath);

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

            EnsureHostCreated();

            return(_host.GetGeneratedSourceFile(VirtualPath.CreateTrailingSlash(virtualPath)));
        }
        public bool Unload()
        {
            Debug.Trace("CBM", "Unload");

            BuildManagerHost host = _host;

            if (host != null)
            {
                _host = null;
                return(host.UnloadAppDomain());
            }

            return(false);
        }
        public string GenerateCode(
            string virtualPath, String virtualFileString, out IDictionary linePragmasTable)
        {
            Debug.Trace("CBM", "GenerateCode " + virtualPath);

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

            EnsureHostCreated();

            return(_host.GenerateCode(VirtualPath.Create(virtualPath), virtualFileString, out linePragmasTable));
        }
        /*
         * Look for a type by name in the assemblies available to this page
         */
        private Type GetType(string typeName)
        {
            // If it contains an assembly name, just call Type.GetType (ASURT 53589)
            if (Util.TypeNameIncludesAssembly(typeName))
            {
                Type t;
                try {
                    t = Type.GetType(typeName, true);
                }
                catch (Exception e) {
                    throw new HttpParseException(null, e, _inputFile, _sourceString, _lineNumber);
                }

                return(t);
            }

            if (_linkedAssemblies == null)
            {
                return(null);
            }

            IDictionaryEnumerator en = _linkedAssemblies.GetEnumerator();

            for (int i = 0; en.MoveNext(); i++)
            {
                Assembly a = (Assembly)en.Key;

                Type t = a.GetType(typeName);

#if DBG
                if (t == null)
                {
                    Debug.Trace("SimpleWebHandlerParser_GetType", "Failed to find type '" + typeName + "' in assembly " + a.GetName().FullName);
                }
                else
                {
                    Debug.Trace("SimpleWebHandlerParser_GetType", "Successfully found type '" + typeName + "' in assembly " + a.GetName().FullName);
                }
#endif

                if (t != null)
                {
                    return(t);
                }
            }

            throw new HttpParseException(
                      HttpRuntime.FormatResourceString(SR.Could_not_create_type, typeName),
                      null, _inputFile, _sourceString, _lineNumber);
        }
Beispiel #22
0
        private Assembly ResolveAssembly(object sender, ResolveEventArgs e)
        {
            Debug.Trace("BuildManagerHost", "ResolveAssembly '" + e.Name + "'");
            if (_assemblyCollection == null)
            return null;

            String assemblyLocation = (String)_assemblyCollection[e.Name];
            if (assemblyLocation == null)
            return null;

            Debug.Trace("BuildManagerHost", "ResolveAssembly: found");

            return Assembly.LoadFrom(assemblyLocation);
        }
        /*
         * Returns the compiler type and parameters that need to be used to build
         * a given file.
         */

        public void GetCompilerParameters(string virtualPath,
                                          out Type codeDomProviderType, out CompilerParameters compilerParameters)
        {
            Debug.Trace("CBM", "GetCompilerParameters " + virtualPath);

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

            EnsureHostCreated();

            _host.GetCompilerParams(VirtualPath.Create(virtualPath), out codeDomProviderType, out compilerParameters);
        }
Beispiel #24
0
        internal void RegisterAssembly(String assemblyName, String assemblyLocation)
        {
            Debug.Trace("BuildManagerHost", "RegisterAssembly '" + assemblyName + "','" + assemblyLocation + "'");

            if (_assemblyCollection == null) {
            lock (_lock) {
                if (_assemblyCollection == null) {
                    _assemblyCollection = Hashtable.Synchronized(new Hashtable());
                }
            }
            }

            AssemblyName asmName = new AssemblyName(assemblyName);
            _assemblyCollection[asmName.FullName] = assemblyLocation;
        }
Beispiel #25
0
        internal void AddFile(string fileName)
        {
            Debug.Trace("DateTimeCombiner", "AddFile: " + fileName);
            if (!FileUtil.FileExists(fileName))
            {
                Debug.Trace("DateTimeCombiner", "Could not find target " + fileName);
                return;
            }

            FileInfo file = new FileInfo(fileName);

            AddDateTime(file.CreationTime);
            AddDateTime(file.LastWriteTime);
            AddFileSize(file.Length);
        }
Beispiel #26
0
        internal static void AbortBackgroundBatchCompilations()
        {
            Debug.Trace("PreservedAssemblyEntry", "AbortBackgroundBatchCompilations: " + _backgroundBatchCompilations.Count + " threads to abort");

            // drain the preservation and compilation mutexes to make sure they are not owned while
            // the threads are aborted
            _mutex.DrainMutex();
            CompilationLock.DrainMutex();

            lock (_backgroundBatchCompilations) {
                foreach (BackgroundBatchCompiler bbc in _backgroundBatchCompilations)
                {
                    bbc.Abort();
                }
            }
        }
        internal void Initialize(VirtualPath virtualPath, string physicalPath)
        {
            Debug.Trace("CBM", "Initialize");

            _virtualPath = virtualPath;

            _physicalPath = FileUtil.FixUpPhysicalDirectory(physicalPath);

            _onAppDomainUnloadedCallback = new WaitCallback(OnAppDomainUnloadedCallback);
            _onAppDomainShutdown         = new WaitCallback(OnAppDomainShutdownCallback);

            _installPath = RuntimeEnvironment.GetRuntimeDirectory();

            // Do not create host during intialization. It will be done on demand.
            //CreateHost();
        }
        public CodeCompileUnit GenerateCodeCompileUnit(
            string virtualPath, String virtualFileString, out Type codeDomProviderType,
            out CompilerParameters compilerParameters, out IDictionary linePragmasTable)
        {
            Debug.Trace("CBM", "GenerateCodeCompileUnit " + virtualPath);

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

            EnsureHostCreated();

            return(_host.GenerateCodeCompileUnit(VirtualPath.Create(virtualPath), virtualFileString,
                                                 out codeDomProviderType, out compilerParameters, out linePragmasTable));
        }
Beispiel #29
0
        private void CacheEntryToMemory(SourceCompilerCachedEntry scce)
        {
            Debug.Assert(_utcStart != DateTime.MinValue);

            // Always add the main compiled file itself as a source dependency
            AddSourceDependency(_physicalPath);

            // Get an array of source file dependencies
            string[] sourceDependencies = Util.StringArrayFromHashtable(_sourceDependencies);

            _cache.UtcInsert(_cacheKey, scce, new CacheDependency(false, sourceDependencies, _utcStart),
                             Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                             CacheItemPriority.NotRemovable, null);

            Debug.Trace("Template", "Caching source code (" + _virtualPath + "," + scce._assembly.GetName().Name + ")");
        }
        // look up item in cache (case-insensitive)
        internal static HttpConfigurationRecord CacheLookup(string vpath)
        {
            string cachekey = CacheKey(vpath);

            HttpConfigurationRecord record = (HttpConfigurationRecord)HttpRuntime.CacheInternal.Get(cachekey);

            Debug.Trace("config_verbose", "Cache " +
                        ((record == null) ? "miss" : "hit") + " on \"" + cachekey + "\"");

            if (record != null)
            {
                record.CheckCachedException();
            }

            return(record);
        }