Exemple #1
0
        internal static void GetCodeDirectoryInformation(
            VirtualPath virtualDir, CodeDirectoryType dirType, StringSet excludedSubdirectories, int index,
            out Type codeDomProviderType, out CompilerParameters compilerParameters,
            out string generatedFilesDir)
        {
            // Compute the full path to the directory we'll use to generate all
            // the code files
            generatedFilesDir = HttpRuntime.CodegenDirInternal + "\\" +
                                sourcesDirectoryPrefix + virtualDir.FileName;

            bool supportLocalization = IsResourceCodeDirectoryType(dirType);

            // the index is used to retrieve the correct referenced assemblies
            BuildProvidersCompiler bpc = new BuildProvidersCompiler(virtualDir, supportLocalization,
                                                                    generatedFilesDir, index);

            CodeDirectoryCompiler cdc = new CodeDirectoryCompiler(virtualDir,
                                                                  dirType, excludedSubdirectories);

            cdc._bpc = bpc;

            // Find all the build provider we want to compile from the code directory
            cdc.FindBuildProviders();

            // Give them to the BuildProvidersCompiler
            bpc.SetBuildProviders(cdc._buildProviders);

            // Generate all the sources into the directory generatedFilesDir
            bpc.GenerateSources(out codeDomProviderType, out compilerParameters);
        }
 internal static BuildResultCompiledGlobalAsaxType GetGlobalAsaxBuildResult(bool isPrecompiledApp)
 {
     string cacheKey = "App_global.asax";
     BuildResultCompiledGlobalAsaxType buildResultFromCache = BuildManager.GetBuildResultFromCache(cacheKey) as BuildResultCompiledGlobalAsaxType;
     if (buildResultFromCache == null)
     {
         if (isPrecompiledApp)
         {
             return null;
         }
         VirtualPath globalAsaxVirtualPath = BuildManager.GlobalAsaxVirtualPath;
         if (!globalAsaxVirtualPath.FileExists())
         {
             return null;
         }
         ApplicationBuildProvider o = new ApplicationBuildProvider();
         o.SetVirtualPath(globalAsaxVirtualPath);
         DateTime utcNow = DateTime.UtcNow;
         BuildProvidersCompiler compiler = new BuildProvidersCompiler(globalAsaxVirtualPath, BuildManager.GenerateRandomAssemblyName("App_global.asax"));
         compiler.SetBuildProviders(new SingleObjectCollection(o));
         CompilerResults results = compiler.PerformBuild();
         buildResultFromCache = (BuildResultCompiledGlobalAsaxType) o.GetBuildResult(results);
         buildResultFromCache.CacheToMemory = false;
         BuildManager.CacheBuildResult(cacheKey, buildResultFromCache, utcNow);
     }
     return buildResultFromCache;
 }
Exemple #3
0
        internal static BuildResultCompiledGlobalAsaxType GetGlobalAsaxBuildResult(bool isPrecompiledApp)
        {
            string cacheKey = "App_global.asax";
            BuildResultCompiledGlobalAsaxType buildResultFromCache = BuildManager.GetBuildResultFromCache(cacheKey) as BuildResultCompiledGlobalAsaxType;

            if (buildResultFromCache == null)
            {
                if (isPrecompiledApp)
                {
                    return(null);
                }
                VirtualPath globalAsaxVirtualPath = BuildManager.GlobalAsaxVirtualPath;
                if (!globalAsaxVirtualPath.FileExists())
                {
                    return(null);
                }
                ApplicationBuildProvider o = new ApplicationBuildProvider();
                o.SetVirtualPath(globalAsaxVirtualPath);
                DateTime utcNow = DateTime.UtcNow;
                BuildProvidersCompiler compiler = new BuildProvidersCompiler(globalAsaxVirtualPath, BuildManager.GenerateRandomAssemblyName("App_global.asax"));
                compiler.SetBuildProviders(new SingleObjectCollection(o));
                CompilerResults results = compiler.PerformBuild();
                buildResultFromCache = (BuildResultCompiledGlobalAsaxType)o.GetBuildResult(results);
                buildResultFromCache.CacheToMemory = false;
                BuildManager.CacheBuildResult(cacheKey, buildResultFromCache, utcNow);
            }
            return(buildResultFromCache);
        }
Exemple #4
0
        internal static Type GetBrowserCapabilitiesType()
        {
            InternalSecurityPermissions.Unrestricted.Assert();
            BuildResult buildResultFromCache = null;

            try
            {
                buildResultFromCache = BuildManager.GetBuildResultFromCache("__browserCapabilitiesCompiler");
                if (buildResultFromCache == null)
                {
                    DateTime         utcNow    = DateTime.UtcNow;
                    VirtualDirectory directory = AppBrowsersVirtualDir.GetDirectory();
                    string           path      = HostingEnvironment.MapPathInternal(AppBrowsersVirtualDir);
                    if ((directory != null) && Directory.Exists(path))
                    {
                        ArrayList list  = new ArrayList();
                        ArrayList list2 = new ArrayList();
                        if (AddBrowserFilesToList(directory, list, false))
                        {
                            AddBrowserFilesToList(directory, list2, true);
                        }
                        else
                        {
                            list2 = list;
                        }
                        if (list2.Count > 0)
                        {
                            ApplicationBrowserCapabilitiesBuildProvider o = new ApplicationBrowserCapabilitiesBuildProvider();
                            foreach (string str2 in list)
                            {
                                o.AddFile(str2);
                            }
                            BuildProvidersCompiler compiler = new BuildProvidersCompiler(null, BuildManager.GenerateRandomAssemblyName("App_Browsers"));
                            compiler.SetBuildProviders(new SingleObjectCollection(o));
                            buildResultFromCache = new BuildResultCompiledType(compiler.PerformBuild().CompiledAssembly.GetType("ASP.ApplicationBrowserCapabilitiesFactory"))
                            {
                                VirtualPath = AppBrowsersVirtualDir
                            };
                            buildResultFromCache.AddVirtualPathDependencies(list2);
                            BuildManager.CacheBuildResult("__browserCapabilitiesCompiler", buildResultFromCache, utcNow);
                        }
                    }
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            if (buildResultFromCache == null)
            {
                return(_browserCapabilitiesFactoryBaseType);
            }
            return(((BuildResultCompiledType)buildResultFromCache).ResultType);
        }
        internal static BuildResultCompiledGlobalAsaxType GetGlobalAsaxBuildResult(bool isPrecompiledApp)
        {
            string cacheKey = BuildManager.GlobalAsaxAssemblyName;

            // Try the cache first, and if it's not there, compile it
            BuildResultCompiledGlobalAsaxType result = BuildManager.GetBuildResultFromCache(cacheKey) as
                                                       BuildResultCompiledGlobalAsaxType;

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

            // If this is a precompiled app don't attempt to compile it
            if (isPrecompiledApp)
            {
                return(null);
            }

            VirtualPath virtualPath = BuildManager.GlobalAsaxVirtualPath;

            // If global.asax doesn't exist, just ignore it
            if (!virtualPath.FileExists())
            {
                return(null);
            }

            // Compile global.asax
            ApplicationBuildProvider buildProvider = new ApplicationBuildProvider();

            buildProvider.SetVirtualPath(virtualPath);

            DateTime utcStart = DateTime.UtcNow;

            BuildProvidersCompiler bpc = new BuildProvidersCompiler(virtualPath /*configPath*/,
                                                                    BuildManager.GenerateRandomAssemblyName(BuildManager.GlobalAsaxAssemblyName));

            // Set the BuildProvider using a single item collection
            bpc.SetBuildProviders(new SingleObjectCollection(buildProvider));

            CompilerResults results = bpc.PerformBuild();

            result = (BuildResultCompiledGlobalAsaxType)buildProvider.GetBuildResult(results);

            // Top level assembliy should not be cached to memory.
            result.CacheToMemory = false;

            // Cache it for next time
            BuildManager.CacheBuildResult(cacheKey, result, utcStart);

            // Return the compiled type
            return(result);
        }
        internal static void GetCodeDirectoryInformation(VirtualPath virtualDir, CodeDirectoryType dirType, StringSet excludedSubdirectories, int index, out Type codeDomProviderType, out CompilerParameters compilerParameters, out string generatedFilesDir)
        {
            generatedFilesDir = HttpRuntime.CodegenDirInternal + @"\Sources_" + virtualDir.FileName;
            bool supportLocalization         = IsResourceCodeDirectoryType(dirType);
            BuildProvidersCompiler compiler  = new BuildProvidersCompiler(virtualDir, supportLocalization, generatedFilesDir, index);
            CodeDirectoryCompiler  compiler2 = new CodeDirectoryCompiler(virtualDir, dirType, excludedSubdirectories)
            {
                _bpc = compiler
            };

            compiler2.FindBuildProviders();
            compiler.SetBuildProviders(compiler2._buildProviders);
            compiler.GenerateSources(out codeDomProviderType, out compilerParameters);
        }
    internal static BuildResultCompiledGlobalAsaxType GetGlobalAsaxBuildResult(bool isPrecompiledApp) {

        string cacheKey = BuildManager.GlobalAsaxAssemblyName;
        
        // Try the cache first, and if it's not there, compile it
        BuildResultCompiledGlobalAsaxType result = BuildManager.GetBuildResultFromCache(cacheKey) as
            BuildResultCompiledGlobalAsaxType;
        if (result != null)
            return result;

        // If this is a precompiled app don't attempt to compile it
        if (isPrecompiledApp)
            return null;

        VirtualPath virtualPath = BuildManager.GlobalAsaxVirtualPath;

        // If global.asax doesn't exist, just ignore it
        if (!virtualPath.FileExists())
            return null;

        // Compile global.asax
        ApplicationBuildProvider buildProvider = new ApplicationBuildProvider();
        buildProvider.SetVirtualPath(virtualPath);

        DateTime utcStart = DateTime.UtcNow;

        BuildProvidersCompiler bpc = new BuildProvidersCompiler(virtualPath /*configPath*/, 
            BuildManager.GenerateRandomAssemblyName(BuildManager.GlobalAsaxAssemblyName));

        // Set the BuildProvider using a single item collection
        bpc.SetBuildProviders(new SingleObjectCollection(buildProvider));

        CompilerResults results = bpc.PerformBuild();

        result = (BuildResultCompiledGlobalAsaxType) buildProvider.GetBuildResult(results);

        // Top level assembliy should not be cached to memory.
        result.CacheToMemory = false;

        // Cache it for next time
        BuildManager.CacheBuildResult(cacheKey, result, utcStart);

        // Return the compiled type
        return result;
    }
 private static BuildResultCompiledType GetThemeBuildResultType(string themeName)
 {
     string cacheKey = null;
     string str = "Theme_" + Util.MakeValidTypeNameFromString(themeName);
     BuildResultCompiledType buildResultFromCache = (BuildResultCompiledType) BuildManager.GetBuildResultFromCache(str);
     if (buildResultFromCache == null)
     {
         cacheKey = "GlobalTheme_" + themeName;
         buildResultFromCache = (BuildResultCompiledType) BuildManager.GetBuildResultFromCache(cacheKey);
     }
     if (buildResultFromCache == null)
     {
         bool gotLock = false;
         try
         {
             CompilationLock.GetLock(ref gotLock);
             buildResultFromCache = (BuildResultCompiledType) BuildManager.GetBuildResultFromCache(str);
             if (buildResultFromCache == null)
             {
                 buildResultFromCache = (BuildResultCompiledType) BuildManager.GetBuildResultFromCache(cacheKey);
             }
             if (buildResultFromCache != null)
             {
                 return buildResultFromCache;
             }
             VirtualPath virtualDirPath = null;
             VirtualPath appThemeVirtualDir = GetAppThemeVirtualDir(themeName);
             PageThemeBuildProvider themeBuildProvider = null;
             VirtualPath configPath = appThemeVirtualDir;
             string str3 = str;
             if (appThemeVirtualDir.DirectoryExists())
             {
                 themeBuildProvider = new PageThemeBuildProvider(appThemeVirtualDir);
             }
             else
             {
                 virtualDirPath = GetGlobalThemeVirtualDir(themeName);
                 if (!virtualDirPath.DirectoryExists())
                 {
                     throw new HttpException(System.Web.SR.GetString("Page_theme_not_found", new object[] { themeName }));
                 }
                 configPath = virtualDirPath;
                 str3 = cacheKey;
                 themeBuildProvider = new GlobalPageThemeBuildProvider(virtualDirPath);
             }
             DateTime utcNow = DateTime.UtcNow;
             AddThemeFilesToBuildProvider(configPath.GetDirectory(), themeBuildProvider, true);
             BuildProvidersCompiler compiler = new BuildProvidersCompiler(configPath, themeBuildProvider.AssemblyNamePrefix + BuildManager.GenerateRandomAssemblyName(themeName));
             compiler.SetBuildProviders(new SingleObjectCollection(themeBuildProvider));
             CompilerResults results = compiler.PerformBuild();
             buildResultFromCache = (BuildResultCompiledType) themeBuildProvider.GetBuildResult(results);
             BuildManager.CacheBuildResult(str3, buildResultFromCache, utcNow);
         }
         finally
         {
             if (gotLock)
             {
                 CompilationLock.ReleaseLock();
             }
         }
     }
     return buildResultFromCache;
 }
        internal static Assembly GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, string assemblyName, StringSet excludedSubdirectories, bool isDirectoryAllowed)
        {
            string path = virtualDir.MapPath();

            if (!isDirectoryAllowed && Directory.Exists(path))
            {
                throw new HttpException(System.Web.SR.GetString("Bar_dir_in_precompiled_app", new object[] { virtualDir }));
            }
            bool        supportLocalization  = IsResourceCodeDirectoryType(dirType);
            string      cacheKey             = assemblyName;
            BuildResult buildResultFromCache = BuildManager.GetBuildResultFromCache(cacheKey);
            Assembly    a = null;

            if ((buildResultFromCache != null) && (buildResultFromCache is BuildResultCompiledAssembly))
            {
                if (buildResultFromCache is BuildResultMainCodeAssembly)
                {
                    _mainCodeBuildResult = (BuildResultMainCodeAssembly)buildResultFromCache;
                }
                a = ((BuildResultCompiledAssembly)buildResultFromCache).ResultAssembly;
                if (!supportLocalization)
                {
                    return(a);
                }
                if (!isDirectoryAllowed)
                {
                    return(a);
                }
                BuildResultResourceAssembly assembly2 = (BuildResultResourceAssembly)buildResultFromCache;
                if (HashCodeCombiner.GetDirectoryHash(virtualDir) == assembly2.ResourcesDependenciesHash)
                {
                    return(a);
                }
            }
            if (!isDirectoryAllowed)
            {
                return(null);
            }
            if ((dirType != CodeDirectoryType.LocalResources) && !StringUtil.StringStartsWithIgnoreCase(path, HttpRuntime.AppDomainAppPathInternal))
            {
                throw new HttpException(System.Web.SR.GetString("Virtual_codedir", new object[] { virtualDir.VirtualPathString }));
            }
            if (!Directory.Exists(path))
            {
                if (dirType != CodeDirectoryType.MainCode)
                {
                    return(null);
                }
                if (!ProfileBuildProvider.HasCompilableProfile)
                {
                    return(null);
                }
            }
            BuildManager.ReportDirectoryCompilationProgress(virtualDir);
            DateTime utcNow = DateTime.UtcNow;
            CodeDirectoryCompiler compiler = new CodeDirectoryCompiler(virtualDir, dirType, excludedSubdirectories);
            string outputAssemblyName      = null;

            if (a != null)
            {
                outputAssemblyName = a.GetName().Name;
                compiler._onlyBuildLocalizedResources = true;
            }
            else
            {
                outputAssemblyName = BuildManager.GenerateRandomAssemblyName(assemblyName);
            }
            BuildProvidersCompiler compiler2 = new BuildProvidersCompiler(virtualDir, supportLocalization, outputAssemblyName);

            compiler._bpc = compiler2;
            compiler.FindBuildProviders();
            compiler2.SetBuildProviders(compiler._buildProviders);
            CompilerResults results = compiler2.PerformBuild();

            if (results != null)
            {
                DateTime time2 = DateTime.UtcNow.AddMilliseconds(3000.0);
                do
                {
                    if (UnsafeNativeMethods.GetModuleHandle(results.PathToAssembly) == IntPtr.Zero)
                    {
                        a = results.CompiledAssembly;
                        goto Label_01E6;
                    }
                    Thread.Sleep(250);
                }while (DateTime.UtcNow <= time2);
                throw new HttpException(System.Web.SR.GetString("Assembly_already_loaded", new object[] { results.PathToAssembly }));
            }
Label_01E6:
            if (a == null)
            {
                return(null);
            }
            if (dirType == CodeDirectoryType.MainCode)
            {
                _mainCodeBuildResult = new BuildResultMainCodeAssembly(a);
                buildResultFromCache = _mainCodeBuildResult;
            }
            else if (supportLocalization)
            {
                buildResultFromCache = new BuildResultResourceAssembly(a);
            }
            else
            {
                buildResultFromCache = new BuildResultCompiledAssembly(a);
            }
            buildResultFromCache.VirtualPath = virtualDir;
            if (BuildManager.OptimizeCompilations && (dirType != CodeDirectoryType.LocalResources))
            {
                buildResultFromCache.AddVirtualPathDependencies(new SingleObjectCollection(virtualDir.AppRelativeVirtualPathString));
            }
            if (dirType != CodeDirectoryType.LocalResources)
            {
                buildResultFromCache.CacheToMemory = false;
            }
            BuildManager.CacheBuildResult(cacheKey, buildResultFromCache, utcNow);
            return(a);
        }
        internal static Type GetBrowserCapabilitiesType()
        {
            //Need to assert here to check directories and files
            InternalSecurityPermissions.Unrestricted.Assert();

            BuildResult result = null;

            try {
                // Try the cache first, and if it's not there, compile it
                result = BuildManager.GetBuildResultFromCache(browerCapabilitiesCacheKey);
                if (result == null)
                {
                    DateTime utcStart = DateTime.UtcNow;

                    VirtualDirectory directory = AppBrowsersVirtualDir.GetDirectory();

                    // first try if app browser dir exists
                    string physicalDir = HostingEnvironment.MapPathInternal(AppBrowsersVirtualDir);

                    /* DevDivBugs 173531
                     * For the App_Browsers scenario, we need to cache the generated browser caps processing
                     * code. We need to add path dependency on all files so that changes to them will
                     * invalidate the cache entry and cause recompilation. */
                    if (directory != null && Directory.Exists(physicalDir))
                    {
                        ArrayList browserFileList             = new ArrayList();
                        ArrayList browserFileDependenciesList = new ArrayList();
                        bool      hasCustomCaps = AddBrowserFilesToList(directory, browserFileList, false);
                        if (hasCustomCaps)
                        {
                            AddBrowserFilesToList(directory, browserFileDependenciesList, true);
                        }
                        else
                        {
                            browserFileDependenciesList = browserFileList;
                        }

                        if (browserFileDependenciesList.Count > 0)
                        {
                            ApplicationBrowserCapabilitiesBuildProvider buildProvider = new ApplicationBrowserCapabilitiesBuildProvider();
                            foreach (string virtualPath in browserFileList)
                            {
                                buildProvider.AddFile(virtualPath);
                            }

                            BuildProvidersCompiler bpc = new BuildProvidersCompiler(null /*configPath*/,
                                                                                    BuildManager.GenerateRandomAssemblyName(BuildManager.AppBrowserCapAssemblyNamePrefix));

                            bpc.SetBuildProviders(new SingleObjectCollection(buildProvider));
                            CompilerResults results  = bpc.PerformBuild();
                            Assembly        assembly = results.CompiledAssembly;
                            // Get the type we want from the assembly
                            Type t = assembly.GetType(
                                BaseCodeDomTreeGenerator.defaultNamespace + "." + ApplicationBrowserCapabilitiesCodeGenerator.FactoryTypeName);
                            // Cache it for next time
                            result             = new BuildResultCompiledType(t);
                            result.VirtualPath = AppBrowsersVirtualDir;
                            result.AddVirtualPathDependencies(browserFileDependenciesList);

                            BuildManager.CacheBuildResult(browerCapabilitiesCacheKey, result, utcStart);
                        }
                    }
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            // Simply return the global factory type.
            if (result == null)
            {
                return(_browserCapabilitiesFactoryBaseType);
            }

            // Return the compiled type
            return(((BuildResultCompiledType)result).ResultType);
        }
    private static BuildResultCompiledType GetThemeBuildResultType(string themeName) {

        string appThemeCacheKey, globalThemeCacheKey = null;

        // First, check if the application theme is cached
        appThemeCacheKey = "Theme_" + Util.MakeValidTypeNameFromString(themeName);
        BuildResultCompiledType result = (BuildResultCompiledType)
            BuildManager.GetBuildResultFromCache(appThemeCacheKey);

        if (result == null) {
            // Then, check if the global theme is cached
            globalThemeCacheKey = "GlobalTheme_" + themeName;
            result = (BuildResultCompiledType) BuildManager.GetBuildResultFromCache(
                globalThemeCacheKey);
        }

        // If we found a theme buildresulttype, return it
        if (result != null)
            return result;

        bool gotLock = false;

        try {
            // Grab the compilation mutex
            CompilationLock.GetLock(ref gotLock);

            // Check the cache again now that we have the mutex
            result = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(appThemeCacheKey);
            if (result == null) {
                result = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(
                    globalThemeCacheKey);
            }

            if (result != null)
                return result;

        // Theme was not found in the caches; check if the directory exists.
        VirtualPath appVirtualDir, globalVirtualDir = null;

        appVirtualDir = GetAppThemeVirtualDir(themeName);
        PageThemeBuildProvider themeBuildProvider = null;

        VirtualPath virtualDir = appVirtualDir;

        string cacheKey = appThemeCacheKey;
        // If the theme directories do not exist, simply throw
        if (appVirtualDir.DirectoryExists()) {
            themeBuildProvider = new PageThemeBuildProvider(appVirtualDir);
        }
        else {
            globalVirtualDir = GetGlobalThemeVirtualDir(themeName);

            if (!globalVirtualDir.DirectoryExists()) {
                throw new HttpException(SR.GetString(SR.Page_theme_not_found, themeName));
            }

            virtualDir = globalVirtualDir;
            cacheKey = globalThemeCacheKey;
            themeBuildProvider = new GlobalPageThemeBuildProvider(globalVirtualDir);
        }

        // The directory exists (either app or global), so compile it
        DateTime utcStart = DateTime.UtcNow;

        VirtualDirectory vdir = virtualDir.GetDirectory();

        // Add all the .skin files to it
        AddThemeFilesToBuildProvider(vdir, themeBuildProvider, true);

        // Use predictable fixed names for theme assemblies.
        BuildProvidersCompiler bpc = new BuildProvidersCompiler(virtualDir, 
            themeBuildProvider.AssemblyNamePrefix + BuildManager.GenerateRandomAssemblyName(themeName));

        // Add the single build provider to the BuildProvidersCompiler
        bpc.SetBuildProviders(new SingleObjectCollection(themeBuildProvider));

        // Compile it
        CompilerResults results = bpc.PerformBuild();

        // Get the Type we care about from the BuildProvider
        result = (BuildResultCompiledType) themeBuildProvider.GetBuildResult(results);

        // Cache it for next time
        BuildManager.CacheBuildResult(cacheKey, result, utcStart);

        }
        finally {
            // Always release the mutex if we had taken it
            if (gotLock) {
                CompilationLock.ReleaseLock();
            }
        }
        return result;
    }
 internal static Type GetBrowserCapabilitiesType()
 {
     InternalSecurityPermissions.Unrestricted.Assert();
     BuildResult buildResultFromCache = null;
     try
     {
         buildResultFromCache = BuildManager.GetBuildResultFromCache("__browserCapabilitiesCompiler");
         if (buildResultFromCache == null)
         {
             DateTime utcNow = DateTime.UtcNow;
             VirtualDirectory directory = AppBrowsersVirtualDir.GetDirectory();
             string path = HostingEnvironment.MapPathInternal(AppBrowsersVirtualDir);
             if ((directory != null) && Directory.Exists(path))
             {
                 ArrayList list = new ArrayList();
                 ArrayList list2 = new ArrayList();
                 if (AddBrowserFilesToList(directory, list, false))
                 {
                     AddBrowserFilesToList(directory, list2, true);
                 }
                 else
                 {
                     list2 = list;
                 }
                 if (list2.Count > 0)
                 {
                     ApplicationBrowserCapabilitiesBuildProvider o = new ApplicationBrowserCapabilitiesBuildProvider();
                     foreach (string str2 in list)
                     {
                         o.AddFile(str2);
                     }
                     BuildProvidersCompiler compiler = new BuildProvidersCompiler(null, BuildManager.GenerateRandomAssemblyName("App_Browsers"));
                     compiler.SetBuildProviders(new SingleObjectCollection(o));
                     buildResultFromCache = new BuildResultCompiledType(compiler.PerformBuild().CompiledAssembly.GetType("ASP.ApplicationBrowserCapabilitiesFactory")) {
                         VirtualPath = AppBrowsersVirtualDir
                     };
                     buildResultFromCache.AddVirtualPathDependencies(list2);
                     BuildManager.CacheBuildResult("__browserCapabilitiesCompiler", buildResultFromCache, utcNow);
                 }
             }
         }
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
     if (buildResultFromCache == null)
     {
         return _browserCapabilitiesFactoryBaseType;
     }
     return ((BuildResultCompiledType) buildResultFromCache).ResultType;
 }
 internal static void GetCodeDirectoryInformation(VirtualPath virtualDir, CodeDirectoryType dirType, StringSet excludedSubdirectories, int index, out Type codeDomProviderType, out CompilerParameters compilerParameters, out string generatedFilesDir)
 {
     generatedFilesDir = HttpRuntime.CodegenDirInternal + @"\Sources_" + virtualDir.FileName;
     bool supportLocalization = IsResourceCodeDirectoryType(dirType);
     BuildProvidersCompiler compiler = new BuildProvidersCompiler(virtualDir, supportLocalization, generatedFilesDir, index);
     CodeDirectoryCompiler compiler2 = new CodeDirectoryCompiler(virtualDir, dirType, excludedSubdirectories) {
         _bpc = compiler
     };
     compiler2.FindBuildProviders();
     compiler.SetBuildProviders(compiler2._buildProviders);
     compiler.GenerateSources(out codeDomProviderType, out compilerParameters);
 }
 internal static Assembly GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, string assemblyName, StringSet excludedSubdirectories, bool isDirectoryAllowed)
 {
     string path = virtualDir.MapPath();
     if (!isDirectoryAllowed && Directory.Exists(path))
     {
         throw new HttpException(System.Web.SR.GetString("Bar_dir_in_precompiled_app", new object[] { virtualDir }));
     }
     bool supportLocalization = IsResourceCodeDirectoryType(dirType);
     string cacheKey = assemblyName;
     BuildResult buildResultFromCache = BuildManager.GetBuildResultFromCache(cacheKey);
     Assembly a = null;
     if ((buildResultFromCache != null) && (buildResultFromCache is BuildResultCompiledAssembly))
     {
         if (buildResultFromCache is BuildResultMainCodeAssembly)
         {
             _mainCodeBuildResult = (BuildResultMainCodeAssembly) buildResultFromCache;
         }
         a = ((BuildResultCompiledAssembly) buildResultFromCache).ResultAssembly;
         if (!supportLocalization)
         {
             return a;
         }
         if (!isDirectoryAllowed)
         {
             return a;
         }
         BuildResultResourceAssembly assembly2 = (BuildResultResourceAssembly) buildResultFromCache;
         if (HashCodeCombiner.GetDirectoryHash(virtualDir) == assembly2.ResourcesDependenciesHash)
         {
             return a;
         }
     }
     if (!isDirectoryAllowed)
     {
         return null;
     }
     if ((dirType != CodeDirectoryType.LocalResources) && !StringUtil.StringStartsWithIgnoreCase(path, HttpRuntime.AppDomainAppPathInternal))
     {
         throw new HttpException(System.Web.SR.GetString("Virtual_codedir", new object[] { virtualDir.VirtualPathString }));
     }
     if (!Directory.Exists(path))
     {
         if (dirType != CodeDirectoryType.MainCode)
         {
             return null;
         }
         if (!ProfileBuildProvider.HasCompilableProfile)
         {
             return null;
         }
     }
     BuildManager.ReportDirectoryCompilationProgress(virtualDir);
     DateTime utcNow = DateTime.UtcNow;
     CodeDirectoryCompiler compiler = new CodeDirectoryCompiler(virtualDir, dirType, excludedSubdirectories);
     string outputAssemblyName = null;
     if (a != null)
     {
         outputAssemblyName = a.GetName().Name;
         compiler._onlyBuildLocalizedResources = true;
     }
     else
     {
         outputAssemblyName = BuildManager.GenerateRandomAssemblyName(assemblyName);
     }
     BuildProvidersCompiler compiler2 = new BuildProvidersCompiler(virtualDir, supportLocalization, outputAssemblyName);
     compiler._bpc = compiler2;
     compiler.FindBuildProviders();
     compiler2.SetBuildProviders(compiler._buildProviders);
     CompilerResults results = compiler2.PerformBuild();
     if (results != null)
     {
         DateTime time2 = DateTime.UtcNow.AddMilliseconds(3000.0);
         do
         {
             if (UnsafeNativeMethods.GetModuleHandle(results.PathToAssembly) == IntPtr.Zero)
             {
                 a = results.CompiledAssembly;
                 goto Label_01E6;
             }
             Thread.Sleep(250);
         }
         while (DateTime.UtcNow <= time2);
         throw new HttpException(System.Web.SR.GetString("Assembly_already_loaded", new object[] { results.PathToAssembly }));
     }
 Label_01E6:
     if (a == null)
     {
         return null;
     }
     if (dirType == CodeDirectoryType.MainCode)
     {
         _mainCodeBuildResult = new BuildResultMainCodeAssembly(a);
         buildResultFromCache = _mainCodeBuildResult;
     }
     else if (supportLocalization)
     {
         buildResultFromCache = new BuildResultResourceAssembly(a);
     }
     else
     {
         buildResultFromCache = new BuildResultCompiledAssembly(a);
     }
     buildResultFromCache.VirtualPath = virtualDir;
     if (BuildManager.OptimizeCompilations && (dirType != CodeDirectoryType.LocalResources))
     {
         buildResultFromCache.AddVirtualPathDependencies(new SingleObjectCollection(virtualDir.AppRelativeVirtualPathString));
     }
     if (dirType != CodeDirectoryType.LocalResources)
     {
         buildResultFromCache.CacheToMemory = false;
     }
     BuildManager.CacheBuildResult(cacheKey, buildResultFromCache, utcNow);
     return a;
 }
        internal static Type GetBrowserCapabilitiesType() {

            //Need to assert here to check directories and files
            InternalSecurityPermissions.Unrestricted.Assert();

            BuildResult result = null;

            try {
                // Try the cache first, and if it's not there, compile it
                result = BuildManager.GetBuildResultFromCache(browerCapabilitiesCacheKey);
                if (result == null) {
                    DateTime utcStart = DateTime.UtcNow;

                    VirtualDirectory directory = AppBrowsersVirtualDir.GetDirectory();

                    // first try if app browser dir exists
                    string physicalDir = HostingEnvironment.MapPathInternal(AppBrowsersVirtualDir);

                    /* DevDivBugs 173531
                     * For the App_Browsers scenario, we need to cache the generated browser caps processing 
                     * code. We need to add path dependency on all files so that changes to them will 
                     * invalidate the cache entry and cause recompilation. */
                    if (directory != null && Directory.Exists(physicalDir)) {
                        ArrayList browserFileList = new ArrayList();
                        ArrayList browserFileDependenciesList = new ArrayList();
                        bool hasCustomCaps = AddBrowserFilesToList(directory, browserFileList, false);
                        if (hasCustomCaps) {
                            AddBrowserFilesToList(directory, browserFileDependenciesList, true);
                        }
                        else {
                            browserFileDependenciesList = browserFileList;
                        }

                        if (browserFileDependenciesList.Count > 0) {
                            ApplicationBrowserCapabilitiesBuildProvider buildProvider = new ApplicationBrowserCapabilitiesBuildProvider();
                            foreach (string virtualPath in browserFileList) {
                                buildProvider.AddFile(virtualPath);
                            }
                            
                            BuildProvidersCompiler bpc = new BuildProvidersCompiler(null /*configPath*/,
                                BuildManager.GenerateRandomAssemblyName(BuildManager.AppBrowserCapAssemblyNamePrefix));
                            
                            bpc.SetBuildProviders(new SingleObjectCollection(buildProvider));
                            CompilerResults results = bpc.PerformBuild();
                            Assembly assembly = results.CompiledAssembly;
                            // Get the type we want from the assembly
                            Type t = assembly.GetType(
                                BaseCodeDomTreeGenerator.defaultNamespace + "." + ApplicationBrowserCapabilitiesCodeGenerator.FactoryTypeName);
                            // Cache it for next time
                            result = new BuildResultCompiledType(t);
                            result.VirtualPath = AppBrowsersVirtualDir;
                            result.AddVirtualPathDependencies(browserFileDependenciesList);

                            BuildManager.CacheBuildResult(browerCapabilitiesCacheKey, result, utcStart);
                        }
                    }
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            // Simply return the global factory type.
            if (result == null)
                return _browserCapabilitiesFactoryBaseType;

            // Return the compiled type
            return ((BuildResultCompiledType)result).ResultType;
        }
Exemple #16
0
        internal static Assembly GetCodeDirectoryAssembly(VirtualPath virtualDir,
                                                          CodeDirectoryType dirType, string assemblyName,
                                                          StringSet excludedSubdirectories, bool isDirectoryAllowed)
        {
            string physicalDir = virtualDir.MapPath();

            if (!isDirectoryAllowed)
            {
                // The directory should never exist in a precompiled app
                if (Directory.Exists(physicalDir))
                {
                    throw new HttpException(SR.GetString(SR.Bar_dir_in_precompiled_app, virtualDir));
                }
            }

            bool supportLocalization = IsResourceCodeDirectoryType(dirType);

            // Determine the proper cache key based on the type of directory we're processing
            string cacheKey = assemblyName;

            // Try the cache first
            BuildResult result         = BuildManager.GetBuildResultFromCache(cacheKey);
            Assembly    resultAssembly = null;

            // If it's cached, just return it
            if (result != null)
            {
                // It should always be a BuildResultCompiledAssembly, though if there is
                // a VirtualPathProvider doing very bad things, it may not (VSWhidbey 341701)
                Debug.Assert(result is BuildResultCompiledAssembly);
                if (result is BuildResultCompiledAssembly)
                {
                    // If it's the main code assembly, keep track of it so we can later call
                    // the AppInitialize method
                    if (result is BuildResultMainCodeAssembly)
                    {
                        Debug.Assert(dirType == CodeDirectoryType.MainCode);
                        Debug.Assert(_mainCodeBuildResult == null);
                        _mainCodeBuildResult = (BuildResultMainCodeAssembly)result;
                    }

                    resultAssembly = ((BuildResultCompiledAssembly)result).ResultAssembly;

                    if (!supportLocalization)
                    {
                        return(resultAssembly);
                    }

                    // We found a preserved resource assembly.  However, we may not be done,
                    // as the culture specific files may have changed.

                    // But don't make any further checks if the directory is not allowed (precomp secenario).
                    // In that case, we should always return the assembly (VSWhidbey 533498)
                    if (!isDirectoryAllowed)
                    {
                        return(resultAssembly);
                    }

                    BuildResultResourceAssembly buildResultResAssembly = (BuildResultResourceAssembly)result;

                    string newResourcesDependenciesHash = HashCodeCombiner.GetDirectoryHash(virtualDir);

                    // If the resources hash (which includes satellites) is up to date, we're done
                    if (newResourcesDependenciesHash == buildResultResAssembly.ResourcesDependenciesHash)
                    {
                        return(resultAssembly);
                    }
                }
            }

            // If app was precompiled, don't attempt compilation
            if (!isDirectoryAllowed)
            {
                return(null);
            }

            // Check whether the virtual dir is mapped to a different application,
            // which we don't support (VSWhidbey 218603).  But don't do this for LocalResource (VSWhidbey 237935)
            if (dirType != CodeDirectoryType.LocalResources && !StringUtil.StringStartsWithIgnoreCase(physicalDir, HttpRuntime.AppDomainAppPathInternal))
            {
                throw new HttpException(SR.GetString(SR.Virtual_codedir, virtualDir.VirtualPathString));
            }

            // If the directory doesn't exist, we may be done
            if (!Directory.Exists(physicalDir))
            {
                // We're definitely done if it's not the main code dir
                if (dirType != CodeDirectoryType.MainCode)
                {
                    return(null);
                }

                // If it is the main code dir, we're only done is there is no profile to compile
                // since the profice gets built as part of the main assembly.
                if (!ProfileBuildProvider.HasCompilableProfile)
                {
                    return(null);
                }
            }


            // Otherwise, compile it

            BuildManager.ReportDirectoryCompilationProgress(virtualDir);

            DateTime utcStart = DateTime.UtcNow;

            CodeDirectoryCompiler cdc = new CodeDirectoryCompiler(virtualDir,
                                                                  dirType, excludedSubdirectories);

            string outputAssemblyName = null;

            if (resultAssembly != null)
            {
                // If resultAssembly is not null, we are in the case where we just need to build
                // the localized resx file in a resources dir (local or global)
                Debug.Assert(supportLocalization);
                outputAssemblyName = resultAssembly.GetName().Name;
                cdc._onlyBuildLocalizedResources = true;
            }
            else
            {
                outputAssemblyName = BuildManager.GenerateRandomAssemblyName(assemblyName);
            }

            BuildProvidersCompiler bpc =
                new BuildProvidersCompiler(virtualDir, supportLocalization, outputAssemblyName);

            cdc._bpc = bpc;

            // Find all the build provider we want to compile from the code directory
            cdc.FindBuildProviders();

            // Give them to the BuildProvidersCompiler
            bpc.SetBuildProviders(cdc._buildProviders);

            // Compile them into an assembly
            CompilerResults results = bpc.PerformBuild();

            // Did we just compile something?
            if (results != null)
            {
                Debug.Assert(result == null);
                Debug.Assert(resultAssembly == null);

                // If there is already a loaded module with the same path, try to wait for it to be unloaded.
                // Otherwise, we would end up loading this old assembly instead of the new one (VSWhidbey 554697)
                DateTime waitLimit = DateTime.UtcNow.AddMilliseconds(3000);
                for (;;)
                {
                    IntPtr hModule = UnsafeNativeMethods.GetModuleHandle(results.PathToAssembly);
                    if (hModule == IntPtr.Zero)
                    {
                        break;
                    }

                    Debug.Trace("CodeDirectoryCompiler", results.PathToAssembly + " is already loaded. Waiting a bit");

                    System.Threading.Thread.Sleep(250);

                    // Stop trying if the timeout was reached
                    if (DateTime.UtcNow > waitLimit)
                    {
                        Debug.Trace("CodeDirectoryCompiler", "Timeout waiting for old assembly to unload: " + results.PathToAssembly);
                        throw new HttpException(SR.GetString(SR.Assembly_already_loaded, results.PathToAssembly));
                    }
                }

                resultAssembly = results.CompiledAssembly;
            }

            // It is possible that there was nothing to compile (and we're not in the
            // satellite resources case)
            if (resultAssembly == null)
            {
                return(null);
            }

            // For the main code directory, use a special BuildResult that takes care of
            // calling AppInitialize if it finds one
            if (dirType == CodeDirectoryType.MainCode)
            {
                // Keep track of it so we can later call the AppInitialize method
                _mainCodeBuildResult = new BuildResultMainCodeAssembly(resultAssembly);

                result = _mainCodeBuildResult;
            }
            else if (supportLocalization)
            {
                result = new BuildResultResourceAssembly(resultAssembly);
            }
            else
            {
                result = new BuildResultCompiledAssembly(resultAssembly);
            }

            result.VirtualPath = virtualDir;

            // If compilations are optimized, we need to include the right dependencies, since we can no longer
            // rely on everything getting wiped out when something in App_Code changes.
            // But don't do this for local resources, since they have their own special way of
            // dealing with dependencies (in BuildResultResourceAssembly.ComputeSourceDependenciesHashCode).
            // It's crucial *not* to do it as it triggers a tricky infinite recursion due to the fact
            // that GetBuildResultFromCacheInternal calls EnsureFirstTimeDirectoryInitForDependencies if
            // there is at least one dependency
            if (BuildManager.OptimizeCompilations && dirType != CodeDirectoryType.LocalResources)
            {
                result.AddVirtualPathDependencies(new SingleObjectCollection(virtualDir.AppRelativeVirtualPathString));
            }

            // Top level assembly should not be cached to memory.  But LocalResources are *not*
            // top level files, and do benefit from memory caching
            if (dirType != CodeDirectoryType.LocalResources)
            {
                result.CacheToMemory = false;
            }

            // Cache it for next time
            BuildManager.CacheBuildResult(cacheKey, result, utcStart);

            return(resultAssembly);
        }
        private static BuildResultCompiledType GetThemeBuildResultType(string themeName)
        {
            string appThemeCacheKey, globalThemeCacheKey = null;

            // First, check if the application theme is cached
            appThemeCacheKey = "Theme_" + Util.MakeValidTypeNameFromString(themeName);
            BuildResultCompiledType result = (BuildResultCompiledType)
                                             BuildManager.GetBuildResultFromCache(appThemeCacheKey);

            if (result == null)
            {
                // Then, check if the global theme is cached
                globalThemeCacheKey = "GlobalTheme_" + themeName;
                result = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(
                    globalThemeCacheKey);
            }

            // If we found a theme buildresulttype, return it
            if (result != null)
            {
                return(result);
            }

            bool gotLock = false;

            try {
                // Grab the compilation mutex
                CompilationLock.GetLock(ref gotLock);

                // Check the cache again now that we have the mutex
                result = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(appThemeCacheKey);
                if (result == null)
                {
                    result = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(
                        globalThemeCacheKey);
                }

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

                // Theme was not found in the caches; check if the directory exists.
                VirtualPath appVirtualDir, globalVirtualDir = null;

                appVirtualDir = GetAppThemeVirtualDir(themeName);
                PageThemeBuildProvider themeBuildProvider = null;

                VirtualPath virtualDir = appVirtualDir;

                string cacheKey = appThemeCacheKey;
                // If the theme directories do not exist, simply throw
                if (appVirtualDir.DirectoryExists())
                {
                    themeBuildProvider = new PageThemeBuildProvider(appVirtualDir);
                }
                else
                {
                    globalVirtualDir = GetGlobalThemeVirtualDir(themeName);

                    if (!globalVirtualDir.DirectoryExists())
                    {
                        throw new HttpException(SR.GetString(SR.Page_theme_not_found, themeName));
                    }

                    virtualDir         = globalVirtualDir;
                    cacheKey           = globalThemeCacheKey;
                    themeBuildProvider = new GlobalPageThemeBuildProvider(globalVirtualDir);
                }

                // The directory exists (either app or global), so compile it
                DateTime utcStart = DateTime.UtcNow;

                VirtualDirectory vdir = virtualDir.GetDirectory();

                // Add all the .skin files to it
                AddThemeFilesToBuildProvider(vdir, themeBuildProvider, true);

                // Use predictable fixed names for theme assemblies.
                BuildProvidersCompiler bpc = new BuildProvidersCompiler(virtualDir,
                                                                        themeBuildProvider.AssemblyNamePrefix + BuildManager.GenerateRandomAssemblyName(themeName));

                // Add the single build provider to the BuildProvidersCompiler
                bpc.SetBuildProviders(new SingleObjectCollection(themeBuildProvider));

                // Compile it
                CompilerResults results = bpc.PerformBuild();

                // Get the Type we care about from the BuildProvider
                result = (BuildResultCompiledType)themeBuildProvider.GetBuildResult(results);

                // Cache it for next time
                BuildManager.CacheBuildResult(cacheKey, result, utcStart);
            }
            finally {
                // Always release the mutex if we had taken it
                if (gotLock)
                {
                    CompilationLock.ReleaseLock();
                }
            }
            return(result);
        }
    internal static Assembly GetCodeDirectoryAssembly(VirtualPath virtualDir,
        CodeDirectoryType dirType, string assemblyName,
        StringSet excludedSubdirectories, bool isDirectoryAllowed) {

        string physicalDir = virtualDir.MapPath();

        if (!isDirectoryAllowed) {

            // The directory should never exist in a precompiled app
            if (Directory.Exists(physicalDir)) {
                throw new HttpException(SR.GetString(SR.Bar_dir_in_precompiled_app, virtualDir));
            }
        }

        bool supportLocalization = IsResourceCodeDirectoryType(dirType);

        // Determine the proper cache key based on the type of directory we're processing
        string cacheKey = assemblyName;

        // Try the cache first
        BuildResult result = BuildManager.GetBuildResultFromCache(cacheKey);
        Assembly resultAssembly = null;

        // If it's cached, just return it
        if (result != null) {

            // It should always be a BuildResultCompiledAssembly, though if there is
            // a VirtualPathProvider doing very bad things, it may not (VSWhidbey 341701)
            Debug.Assert(result is BuildResultCompiledAssembly);
            if (result is BuildResultCompiledAssembly) {

                // If it's the main code assembly, keep track of it so we can later call
                // the AppInitialize method
                if (result is BuildResultMainCodeAssembly) {
                    Debug.Assert(dirType == CodeDirectoryType.MainCode);
                    Debug.Assert(_mainCodeBuildResult == null);
                    _mainCodeBuildResult = (BuildResultMainCodeAssembly) result;
                }

                resultAssembly = ((BuildResultCompiledAssembly)result).ResultAssembly;

                if (!supportLocalization)
                    return resultAssembly;

                // We found a preserved resource assembly.  However, we may not be done,
                // as the culture specific files may have changed.

                // But don't make any further checks if the directory is not allowed (precomp secenario).
                // In that case, we should always return the assembly (VSWhidbey 533498)
                if (!isDirectoryAllowed)
                    return resultAssembly;

                BuildResultResourceAssembly buildResultResAssembly = (BuildResultResourceAssembly)result;

                string newResourcesDependenciesHash = HashCodeCombiner.GetDirectoryHash(virtualDir);

                // If the resources hash (which includes satellites) is up to date, we're done
                if (newResourcesDependenciesHash == buildResultResAssembly.ResourcesDependenciesHash)
                    return resultAssembly;
           }
        }

        // If app was precompiled, don't attempt compilation
        if (!isDirectoryAllowed)
            return null;

        // Check whether the virtual dir is mapped to a different application,
        // which we don't support (VSWhidbey 218603).  But don't do this for LocalResource (VSWhidbey 237935)
        if (dirType != CodeDirectoryType.LocalResources && !StringUtil.StringStartsWithIgnoreCase(physicalDir, HttpRuntime.AppDomainAppPathInternal)) {
            throw new HttpException(SR.GetString(SR.Virtual_codedir, virtualDir.VirtualPathString));
        }

        // If the directory doesn't exist, we may be done
        if (!Directory.Exists(physicalDir)) {

            // We're definitely done if it's not the main code dir
            if (dirType != CodeDirectoryType.MainCode)
                return null;

            // If it is the main code dir, we're only done is there is no profile to compile
            // since the profice gets built as part of the main assembly.
            if (!ProfileBuildProvider.HasCompilableProfile)
                return null;
        }


        // Otherwise, compile it

        BuildManager.ReportDirectoryCompilationProgress(virtualDir);

        DateTime utcStart = DateTime.UtcNow;

        CodeDirectoryCompiler cdc = new CodeDirectoryCompiler(virtualDir,
            dirType, excludedSubdirectories);

        string outputAssemblyName = null;

        if (resultAssembly != null) {
            // If resultAssembly is not null, we are in the case where we just need to build
            // the localized resx file in a resources dir (local or global)
            Debug.Assert(supportLocalization);
            outputAssemblyName = resultAssembly.GetName().Name;
            cdc._onlyBuildLocalizedResources = true;
        }
        else {
            outputAssemblyName = BuildManager.GenerateRandomAssemblyName(assemblyName);
        }

        BuildProvidersCompiler bpc = 
            new BuildProvidersCompiler(virtualDir, supportLocalization, outputAssemblyName);

        cdc._bpc = bpc;

        // Find all the build provider we want to compile from the code directory
        cdc.FindBuildProviders();

        // Give them to the BuildProvidersCompiler
        bpc.SetBuildProviders(cdc._buildProviders);

        // Compile them into an assembly
        CompilerResults results = bpc.PerformBuild();

        // Did we just compile something?
        if (results != null) {
            Debug.Assert(result == null);
            Debug.Assert(resultAssembly == null);

            // If there is already a loaded module with the same path, try to wait for it to be unloaded.
            // Otherwise, we would end up loading this old assembly instead of the new one (VSWhidbey 554697)
            DateTime waitLimit = DateTime.UtcNow.AddMilliseconds(3000);
            for (;;) {
                IntPtr hModule = UnsafeNativeMethods.GetModuleHandle(results.PathToAssembly);
                if (hModule == IntPtr.Zero)
                    break;

                Debug.Trace("CodeDirectoryCompiler", results.PathToAssembly + " is already loaded. Waiting a bit");

                System.Threading.Thread.Sleep(250);

                // Stop trying if the timeout was reached
                if (DateTime.UtcNow > waitLimit) {
                    Debug.Trace("CodeDirectoryCompiler", "Timeout waiting for old assembly to unload: " + results.PathToAssembly);
                    throw new HttpException(SR.GetString(SR.Assembly_already_loaded, results.PathToAssembly));
                }
            }

            resultAssembly = results.CompiledAssembly;
        }

        // It is possible that there was nothing to compile (and we're not in the
        // satellite resources case)
        if (resultAssembly == null)
            return null;

        // For the main code directory, use a special BuildResult that takes care of
        // calling AppInitialize if it finds one
        if (dirType == CodeDirectoryType.MainCode) {
            // Keep track of it so we can later call the AppInitialize method
            _mainCodeBuildResult = new BuildResultMainCodeAssembly(resultAssembly);

            result = _mainCodeBuildResult;
        }
        else if (supportLocalization) {
            result = new BuildResultResourceAssembly(resultAssembly);
        }
        else {
            result = new BuildResultCompiledAssembly(resultAssembly);
        }

        result.VirtualPath = virtualDir;

        // If compilations are optimized, we need to include the right dependencies, since we can no longer
        // rely on everything getting wiped out when something in App_Code changes.
        // But don't do this for local resources, since they have their own special way of
        // dealing with dependencies (in BuildResultResourceAssembly.ComputeSourceDependenciesHashCode).
        // It's crucial *not* to do it as it triggers a tricky infinite recursion due to the fact
        // that GetBuildResultFromCacheInternal calls EnsureFirstTimeDirectoryInitForDependencies if
        // there is at least one dependency
        if (BuildManager.OptimizeCompilations && dirType != CodeDirectoryType.LocalResources) {
            result.AddVirtualPathDependencies(new SingleObjectCollection(virtualDir.AppRelativeVirtualPathString));
        }

        // Top level assembly should not be cached to memory.  But LocalResources are *not*
        // top level files, and do benefit from memory caching
        if (dirType != CodeDirectoryType.LocalResources)
            result.CacheToMemory = false;

        // Cache it for next time
        BuildManager.CacheBuildResult(cacheKey, result, utcStart);

        return resultAssembly;
    }
    internal static void GetCodeDirectoryInformation(
        VirtualPath virtualDir, CodeDirectoryType dirType, StringSet excludedSubdirectories, int index,
        out Type codeDomProviderType, out CompilerParameters compilerParameters,
        out string generatedFilesDir) {

        // Compute the full path to the directory we'll use to generate all
        // the code files
        generatedFilesDir = HttpRuntime.CodegenDirInternal + "\\" + 
            sourcesDirectoryPrefix + virtualDir.FileName;

        bool supportLocalization = IsResourceCodeDirectoryType(dirType);

        // the index is used to retrieve the correct referenced assemblies
        BuildProvidersCompiler bpc = new BuildProvidersCompiler(virtualDir, supportLocalization,
            generatedFilesDir, index);

        CodeDirectoryCompiler cdc = new CodeDirectoryCompiler(virtualDir,
            dirType, excludedSubdirectories);
        cdc._bpc = bpc;

        // Find all the build provider we want to compile from the code directory
        cdc.FindBuildProviders();

        // Give them to the BuildProvidersCompiler
        bpc.SetBuildProviders(cdc._buildProviders);

        // Generate all the sources into the directory generatedFilesDir
        bpc.GenerateSources(out codeDomProviderType, out compilerParameters);
    }
        private BuildResult CompileWebFile(VirtualPath virtualPath) {

            BuildResult result = null;
            string cacheKey = null;

            if (_topLevelFilesCompiledCompleted) {

                VirtualPath parentPath = virtualPath.Parent;

                // First, try to batch the directory if enabled
                if (IsBatchEnabledForDirectory(parentPath)) {
                    BatchCompileWebDirectory(null, parentPath, true /*ignoreErrors*/);

                    // If successful, it would have been cached to memory
                    cacheKey = GetCacheKeyFromVirtualPath(virtualPath);
                    result = _memoryCache.GetBuildResult(cacheKey);

                    if (result == null && DelayLoadType.Enabled) {
                        // We might not have cached the result in the memory cache
                        // if we are trying to delay loading the assembly.
                        result = GetBuildResultFromCache(cacheKey);
                    }

                    if (result != null) {
                        // If what we found in the cache is a CompileError, rethrow the exception
                        if (result is BuildResultCompileError) {
                            throw ((BuildResultCompileError)result).CompileException;
                        }

                        return result;
                    }
                }
            }


            DateTime utcStart = DateTime.UtcNow;

            // Name the assembly based on the virtual path, in order to get a recognizable name
            string outputAssemblyName = BuildManager.WebAssemblyNamePrefix +
                BuildManager.GenerateRandomAssemblyName(
                GetGeneratedAssemblyBaseName(virtualPath), false /*topLevel*/);


            BuildProvidersCompiler bpc = new BuildProvidersCompiler(virtualPath /*configPath*/, outputAssemblyName);

            // Create a BuildProvider based on the virtual path
            BuildProvider buildProvider = CreateBuildProvider(virtualPath, bpc.CompConfig,
                bpc.ReferencedAssemblies, true /*failIfUnknown*/);

            // Set the BuildProvider using a single item collection
            bpc.SetBuildProviders(new SingleObjectCollection(buildProvider));

            // Compile it
            CompilerResults results;

            try {
                results = bpc.PerformBuild();
                result = buildProvider.GetBuildResult(results);
            }
            catch (HttpCompileException e) {

                // If we're not supposed to cache the exception, just rethrow it
                if (e.DontCache)
                    throw;

                result = new BuildResultCompileError(virtualPath, e);

                // Add the dependencies to the compile error build provider, so that
                // we will retry compilation when a dependency changes
                buildProvider.SetBuildResultDependencies(result);

                // Remember the virtualpath dependencies, so that we will correctly
                // invalidate buildresult when depdency changes.
                e.VirtualPathDependencies = buildProvider.VirtualPathDependencies;

                // Cache it for next time
                CacheVPathBuildResultInternal(virtualPath, result, utcStart);

                // Set the DontCache flag, so that the exception will not be incorrectly
                // cached again lower down the stack (VSWhidbey 128234)
                e.DontCache = true;

                throw;
            }

            if (result == null)
                return null;

            // Cache it for next time
            CacheVPathBuildResultInternal(virtualPath, result, utcStart);

            if (!_precompilingApp && BuildResultCompiledType.UsesDelayLoadType(result)) {
                // The result uses DelayLoadType, which should not get exposed.
                // If we are not performing precompilation, then we should
                // get the actual result from cache and return that instead.
                if (cacheKey == null) {
                    cacheKey = GetCacheKeyFromVirtualPath(virtualPath);
                }
                result = BuildManager.GetBuildResultFromCache(cacheKey);
            }

            return result;
        }
Exemple #21
0
        private static BuildResultCompiledType GetThemeBuildResultType(string themeName)
        {
            string cacheKey = null;
            string str      = "Theme_" + Util.MakeValidTypeNameFromString(themeName);
            BuildResultCompiledType buildResultFromCache = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(str);

            if (buildResultFromCache == null)
            {
                cacheKey             = "GlobalTheme_" + themeName;
                buildResultFromCache = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(cacheKey);
            }
            if (buildResultFromCache == null)
            {
                bool gotLock = false;
                try
                {
                    CompilationLock.GetLock(ref gotLock);
                    buildResultFromCache = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(str);
                    if (buildResultFromCache == null)
                    {
                        buildResultFromCache = (BuildResultCompiledType)BuildManager.GetBuildResultFromCache(cacheKey);
                    }
                    if (buildResultFromCache != null)
                    {
                        return(buildResultFromCache);
                    }
                    VirtualPath            virtualDirPath     = null;
                    VirtualPath            appThemeVirtualDir = GetAppThemeVirtualDir(themeName);
                    PageThemeBuildProvider themeBuildProvider = null;
                    VirtualPath            configPath         = appThemeVirtualDir;
                    string str3 = str;
                    if (appThemeVirtualDir.DirectoryExists())
                    {
                        themeBuildProvider = new PageThemeBuildProvider(appThemeVirtualDir);
                    }
                    else
                    {
                        virtualDirPath = GetGlobalThemeVirtualDir(themeName);
                        if (!virtualDirPath.DirectoryExists())
                        {
                            throw new HttpException(System.Web.SR.GetString("Page_theme_not_found", new object[] { themeName }));
                        }
                        configPath         = virtualDirPath;
                        str3               = cacheKey;
                        themeBuildProvider = new GlobalPageThemeBuildProvider(virtualDirPath);
                    }
                    DateTime utcNow = DateTime.UtcNow;
                    AddThemeFilesToBuildProvider(configPath.GetDirectory(), themeBuildProvider, true);
                    BuildProvidersCompiler compiler = new BuildProvidersCompiler(configPath, themeBuildProvider.AssemblyNamePrefix + BuildManager.GenerateRandomAssemblyName(themeName));
                    compiler.SetBuildProviders(new SingleObjectCollection(themeBuildProvider));
                    CompilerResults results = compiler.PerformBuild();
                    buildResultFromCache = (BuildResultCompiledType)themeBuildProvider.GetBuildResult(results);
                    BuildManager.CacheBuildResult(str3, buildResultFromCache, utcNow);
                }
                finally
                {
                    if (gotLock)
                    {
                        CompilationLock.ReleaseLock();
                    }
                }
            }
            return(buildResultFromCache);
        }