예제 #1
0
        protected override string GetClassType(BaseCompiler compiler, SimpleWebHandlerParser parser)
        {
            if (parser != null)
            {
                return(parser.ClassName);
            }

            return(null);
        }
예제 #2
0
        protected override string GetClassType(BaseCompiler compiler, TemplateParser parser)
        {
            if (compiler != null)
            {
                return(compiler.MainClassType);
            }

            return(null);
        }
예제 #3
0
        internal override void GenerateCode()
        {
            TParser parser = Parse();

            _compiler = CreateCompiler(parser);
            if (NeedsConstructType)
            {
                _compiler.ConstructType();
            }
            _codeGenerated = true;
        }
		public static CompilerResults Compile (BaseCompiler compiler)
		{
			Cache cache = HttpRuntime.InternalCache;
			string key = cachePrefix + compiler.Parser.InputFile;
			CompilerResults results = (CompilerResults) cache [key];

#if NET_2_0
			if (!compiler.IsRebuildingPartial)
#endif
			if (results != null)
				return results;

			object ticket;
			bool acquired = AcquireCompilationTicket (key, out ticket);

			try {
				Monitor.Enter (ticket);
				results = (CompilerResults) cache [key];
#if NET_2_0
				if (!compiler.IsRebuildingPartial)
#endif
				if (results != null)
					return results;

#if NET_2_0
				CodeDomProvider comp = compiler.Provider;
#else
				ICodeCompiler comp = compiler.Compiler;
#endif
				CompilerParameters options = compiler.CompilerParameters;
				GetExtraAssemblies (options);
				results = comp.CompileAssemblyFromDom (options, compiler.CompileUnit);
				ArrayList dependencies = compiler.Parser.Dependencies;
				if (dependencies != null && dependencies.Count > 0) {
					string [] deps = (string []) dependencies.ToArray (typeof (string));
					HttpContext ctx = HttpContext.Current;
					HttpRequest req = ctx != null ? ctx.Request : null;

					if (req == null)
						throw new HttpException ("No current context, cannot compile.");
				
					for (int i = 0; i < deps.Length; i++)
						deps [i] = req.MapPath (deps [i]);
				
					cache.Insert (key, results, new CacheDependency (deps));
				}
			} finally {
				Monitor.Exit (ticket);
				if (acquired)
					ReleaseCompilationTicket (key);
			}

			return results;
		}
		public static CompilerResults Compile (BaseCompiler compiler)
		{
			Cache cache = HttpRuntime.Cache;
			string key = cachePrefix + compiler.Parser.InputFile;
			CompilerResults results = (CompilerResults) cache [key];
			if (results != null)
				return results;

			lock (compilationLock) {
				results = (CompilerResults) cache [key];
				if (results != null)
					return results;

				ICodeCompiler comp = compiler.Compiler;
				results = comp.CompileAssemblyFromDom (compiler.CompilerParameters, compiler.Unit);
				string [] deps = (string []) compiler.Parser.Dependencies.ToArray (typeof (string));
				cache.InsertPrivate (key, results, new CacheDependency (deps));
			}

			return results;
		}
예제 #6
0
 protected abstract string GetClassType(BaseCompiler compiler, TParser parser);
예제 #7
0
 protected virtual Type LoadTypeFromBin(BaseCompiler compiler, TParser parser)
 {
     return(null);
 }
예제 #8
0
        protected virtual void GenerateCode(AssemblyBuilder assemblyBuilder, TParser parser, BaseCompiler compiler)
        {
            CodeCompileUnit unit = _compiler.CompileUnit;

            if (unit == null)
            {
                throw new HttpException("Unable to generate source code.");
            }

            assemblyBuilder.AddCodeCompileUnit(this, unit);
        }
예제 #9
0
 protected override Type LoadTypeFromBin(BaseCompiler compiler, SimpleWebHandlerParser parser)
 {
     return(parser.GetTypeFromBin(parser.ClassName));
 }
예제 #10
0
        protected override void GenerateCode(AssemblyBuilder assemblyBuilder, SimpleWebHandlerParser parser, BaseCompiler compiler)
        {
            if (assemblyBuilder == null || parser == null)
            {
                return;
            }

            string programCode = parser.Program.Trim();

            if (String.IsNullOrEmpty(programCode))
            {
                _needLoadFromBin = true;
                return;
            }

            _needLoadFromBin = false;
            using (TextWriter writer = assemblyBuilder.CreateCodeFile(this))
                writer.WriteLine(programCode);
        }
        public static CompilerResults Compile(BaseCompiler compiler)
        {
            Cache           cache   = HttpRuntime.InternalCache;
            string          key     = cachePrefix + compiler.Parser.InputFile;
            CompilerResults results = (CompilerResults)cache [key];

            if (!compiler.IsRebuildingPartial)
            {
                if (results != null)
                {
                    return(results);
                }
            }

            object ticket;
            bool   acquired = AcquireCompilationTicket(key, out ticket);

            try
            {
                Monitor.Enter(ticket);
                results = (CompilerResults)cache [key];
                if (!compiler.IsRebuildingPartial)
                {
                    if (results != null)
                    {
                        return(results);
                    }
                }

                CodeDomProvider    comp    = compiler.Provider;
                CompilerParameters options = compiler.CompilerParameters;
                GetExtraAssemblies(options);
                results = comp.CompileAssemblyFromDom(options, compiler.CompileUnit);
                List <string> dependencies = compiler.Parser.Dependencies;
                if (dependencies != null && dependencies.Count > 0)
                {
                    string []   deps = dependencies.ToArray();
                    HttpContext ctx  = HttpContext.Current;
                    HttpRequest req  = ctx != null ? ctx.Request : null;

                    if (req == null)
                    {
                        throw new HttpException("No current context, cannot compile.");
                    }

                    for (int i = 0; i < deps.Length; i++)
                    {
                        deps [i] = req.MapPath(deps [i]);
                    }

                    cache.Insert(key, results, new CacheDependency(deps));
                }
            }
            finally
            {
                Monitor.Exit(ticket);
                if (acquired)
                {
                    ReleaseCompilationTicket(key);
                }
            }

            return(results);
        }
        public static CompilerResults Compile(string language, string key, string file, ArrayList assemblies, bool debug)
        {
            Cache           cache   = HttpRuntime.InternalCache;
            CompilerResults results = (CompilerResults)cache [cachePrefix + key];

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

            if (!Directory.Exists(dynamicBase))
            {
                Directory.CreateDirectory(dynamicBase);
            }

            object ticket;
            bool   acquired = AcquireCompilationTicket(cachePrefix + key, out ticket);

            try
            {
                Monitor.Enter(ticket);
                results = (CompilerResults)cache [cachePrefix + key];
                if (results != null)
                {
                    return(results);
                }

                CodeDomProvider provider = null;
                int             warningLevel;
                string          compilerOptions;
                string          tempdir;

                provider = BaseCompiler.CreateProvider(language, out compilerOptions, out warningLevel, out tempdir);
                if (provider == null)
                {
                    throw new HttpException("Configuration error. Language not supported: " +
                                            language, 500);
                }
                CodeDomProvider    compiler = provider;
                CompilerParameters options  = GetOptions(assemblies);
                options.IncludeDebugInformation = debug;
                options.WarningLevel            = warningLevel;
                options.CompilerOptions         = compilerOptions;

                TempFileCollection tempcoll    = new TempFileCollection(tempdir, true);
                string             dllfilename = Path.GetFileName(tempcoll.AddExtension("dll", true));
                options.OutputAssembly = Path.Combine(dynamicBase, dllfilename);
                results = compiler.CompileAssemblyFromFile(options, file);
                ArrayList realdeps = new ArrayList(assemblies.Count + 1);
                realdeps.Add(file);
                for (int i = assemblies.Count - 1; i >= 0; i--)
                {
                    string current = (string)assemblies [i];
                    if (Path.IsPathRooted(current))
                    {
                        realdeps.Add(current);
                    }
                }

                string [] deps = (string [])realdeps.ToArray(typeof(string));
                cache.Insert(cachePrefix + key, results, new CacheDependency(deps));
            }
            finally
            {
                Monitor.Exit(ticket);
                if (acquired)
                {
                    ReleaseCompilationTicket(cachePrefix + key);
                }
            }

            return(results);
        }
예제 #13
0
        private static void BasicBatchCompilation(HttpContext context,
                                                  CompilerInfo compInfo, PagesWithSameCompilerInfo pwsci)
        {
            ICodeCompiler compiler = pwsci.CodeProvider.CreateCompiler();

            Debug.Trace("Batching", "Compiling " + pwsci.PageCount + " pages");

            CompilerParameters compilParams = compInfo.CompilParams;

            compilParams.TempFiles = new TempFileCollection(HttpRuntime.CodegenDirInternal);

            // Create the resource file (shared by all the pages in the bucket)
            if (pwsci._stringResourceBuilder.HasStrings)
            {
                string resFileName = compilParams.TempFiles.AddExtension("res");
                pwsci._stringResourceBuilder.CreateResourceFile(resFileName);
                compilParams.Win32Resource = resFileName;
            }

            // Never generate debug code when we're batching
            compilParams.TempFiles.KeepFiles     = false;
            compilParams.IncludeDebugInformation = false;

            // Compute a table of all the assemblies used by all the pages in the
            // bucket, removing duplicates
            Hashtable allAssemblies = new Hashtable();

            // Place all the generated source file names in an array
            string[] files     = new string[pwsci.PageCount];
            int      fileCount = 0;

            foreach (BatchCompilationEntry e in pwsci.Pages)
            {
                Debug.Assert(FileUtil.FileExists(e.GeneratedSourceFile), e.GeneratedSourceFile + " is missing!");

                files[fileCount++] = e.GeneratedSourceFile;

                // Add all the assemblies
                if (e.AssemblyDependencies != null)
                {
                    foreach (Assembly assembly in e.AssemblyDependencies.Keys)
                    {
                        string assemblyName = Util.GetAssemblyCodeBase(assembly);
                        allAssemblies[assemblyName] = null;
                    }
                }
            }
            Debug.Assert(fileCount == pwsci.PageCount, "fileCount == pwsci.PageCount");

            // Now, add all the (non-duplicate) assemblies to the compilParams
            foreach (string aname in allAssemblies.Keys)
            {
                compilParams.ReferencedAssemblies.Add(aname);
            }

            // Compile them all together into an assembly
            CompilerResults results;

            try {
                results = compiler.CompileAssemblyFromFileBatch(compilParams, files);
            }
            catch (Exception e) {
                Debug.Trace("Batching", "Compilation failed!  " + e.Message);
                throw new HttpUnhandledException(HttpRuntime.FormatResourceString(SR.CompilationUnhandledException, pwsci.CodeProvider.GetType().FullName), e);
            }
            finally {
                // Delete all the generated source files
                for (int i = 0; i < fileCount; i++)
                {
                    File.Delete(files[i]);
                }
            }

            BaseCompiler.ThrowIfCompilerErrors(results, pwsci.CodeProvider, null, null, null);

            // Note the assembly that everything ended up in
            foreach (BatchCompilationEntry e in pwsci.Pages)
            {
                e.SetTargetAssembly(results.CompiledAssembly);
                CacheResults(context, e);

                // Do some cleanup
                e.PostCompilation();
            }
        }
예제 #14
0
        private SourceCompilerCachedEntry CompileAndCache()
        {
            BaseCompiler.GenerateCompilerParameters(_compilParams);

            // Get the set of config assemblies for our context
            IDictionary configAssemblies = CompilationConfiguration.GetAssembliesFromContext(_context);

            if (_assemblies == null)
            {
                _assemblies = new Hashtable();
            }

            // Add all the assemblies from the config object to the hashtable
            // This guarantees uniqueness
            if (configAssemblies != null)
            {
                foreach (Assembly asm in configAssemblies.Values)
                {
                    _assemblies[asm] = null;
                }
            }

            // And the assembly of the application object (global.asax)
            _assemblies[HttpApplicationFactory.ApplicationType.Assembly] = null;

            // Now add all the passed in assemblies to the compilParams
            foreach (Assembly asm in _assemblies.Keys)
            {
                _compilParams.ReferencedAssemblies.Add(Util.GetAssemblyCodeBase(asm));
            }

            // Instantiate the Compiler
            CodeDomProvider codeProvider = (CodeDomProvider)HttpRuntime.CreatePublicInstance(_compilerType);
            ICodeCompiler   compiler     = codeProvider.CreateCompiler();
            CompilerResults results;

            // Compile the source file or string into an assembly

            try {
                _utcStart = DateTime.UtcNow;

                // If we have a source file, read it as a string and compile it.  This way,
                // the compiler never needs to read the original file, avoiding permission
                // issues (see ASURT 112718)
                if (_sourceString == null)
                {
                    _sourceString = Util.StringFromFile(_physicalPath, _context);

                    // Put in some context so that the file can be debugged.
                    _linePragma = new CodeLinePragma(_physicalPath, 1);
                }

                CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(_sourceString);
                snippetCompileUnit.LinePragma = _linePragma;
                results = compiler.CompileAssemblyFromDom(_compilParams, snippetCompileUnit);
            }
            catch (Exception e) {
                throw new HttpUnhandledException(HttpRuntime.FormatResourceString(SR.CompilationUnhandledException, codeProvider.GetType().FullName), e);
            }

            BaseCompiler.ThrowIfCompilerErrors(results, codeProvider,
                                               null, _physicalPath, _sourceString);

            SourceCompilerCachedEntry scce = new SourceCompilerCachedEntry();

            // Load the assembly
            scce._assembly = results.CompiledAssembly;

            // If we have a type name, load the type from the assembly
            if (_typeName != null)
            {
                scce._type = scce._assembly.GetType(_typeName);

                // If the type could not be loaded, delete the assembly and rethrow
                if (scce._type == null)
                {
                    PreservedAssemblyEntry.RemoveOutOfDateAssembly(scce._assembly.GetName().Name);

                    // Remember why we failed
                    _typeNotFoundInAssembly = true;

                    throw new HttpException(
                              HttpRuntime.FormatResourceString(SR.Could_not_create_type, _typeName));
                }
            }

            CacheEntryToDisk(scce);
            CacheEntryToMemory(scce);

            return(scce);
        }