CreateCompiler() private method

private CreateCompiler ( ) : ICodeCompiler
return ICodeCompiler
		public static Assembly Compile(CodeDomProvider cp, string scriptCode, IList assemblies)
		{
			ICodeCompiler ic = cp.CreateCompiler();
			CompilerParameters cpar = GetCompilerParameters(assemblies);
			CompilerResults cr = ic.CompileAssemblyFromSource(cpar, scriptCode);

			bool errors = false;

			if (cr.Errors.Count > 0)
			{
				StringBuilder sb = new StringBuilder("Error compiling the composition script:\n");
				foreach (CompilerError ce in cr.Errors)
				{
					if (!ce.IsWarning)
					{
						errors = true;

						sb.Append("\nError number:\t")
							.Append(ce.ErrorNumber)
							.Append("\nMessage:\t ")
							.Append(ce.ErrorText)
							.Append("\nLine number:\t")
							.Append(ce.Line);
					}
				}
				if (errors)
				{
					throw new PicoCompositionException(sb.ToString());
				}
			}

			return cr.CompiledAssembly;
		}
		public override Type GetCompiledType ()
		{
			Type type = CachingCompiler.GetTypeFromCache (parser.PhysicalPath);
			if (type != null)
				return type;

			if (parser.Program.Trim () == "") {
				type = parser.GetTypeFromBin (parser.ClassName);
				CachingCompiler.InsertType (type, parser.PhysicalPath);
				return type;
			}

			string lang = parser.Language;
			CompilationConfiguration config;
			config = CompilationConfiguration.GetInstance (parser.Context);
			provider = config.GetProvider (lang);
			if (provider == null)
				throw new HttpException ("Configuration error. Language not supported: " +
							  lang, 500);

			compiler = provider.CreateCompiler ();

			compilerParameters = CachingCompiler.GetOptions (parser.Assemblies);
			compilerParameters.IncludeDebugInformation = parser.Debug;
			compilerParameters.CompilerOptions = config.GetCompilerOptions (lang);
			compilerParameters.WarningLevel = config.GetWarningLevel (lang);

			bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);

			TempFileCollection tempcoll;
			tempcoll = new TempFileCollection (config.TempDirectory, keepFiles);
			compilerParameters.TempFiles = tempcoll;

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

			inputFile = tempcoll.AddExtension (provider.FileExtension);
			Stream st = File.OpenWrite (inputFile);
			StreamWriter sw = new StreamWriter (st);
			sw.WriteLine (parser.Program);
			sw.Close ();

			string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));

			compilerParameters.OutputAssembly = Path.Combine (dynamicBase, dllfilename);

			CompilerResults results = CachingCompiler.Compile (this);
			CheckCompilerErrors (results);
			if (results.CompiledAssembly == null)
				throw new CompilationException (inputFile, results.Errors,
					"No assembly returned after compilation!?");

			results.TempFiles.Delete ();
			type = results.CompiledAssembly.GetType (parser.ClassName, true);
			CachingCompiler.InsertType (type, parser.PhysicalPath);
			return type;
		}
		public Assembly Compile(CodeDomProvider codeDomProvider, object scriptCode, IList assemblies )
		{
			ICodeCompiler codeCompiler = codeDomProvider.CreateCompiler();
			CompilerParameters compilerParameters = GetCompilerParameters(assemblies);
			CompilerResults compilerResults = null;

			if(scriptCode is string) 
			{
				compilerResults = codeCompiler.CompileAssemblyFromSource(compilerParameters, scriptCode as string);
			}
			else
			{
				compilerResults = codeCompiler.CompileAssemblyFromDom(compilerParameters, scriptCode as CodeCompileUnit);
			}

			handleErrors(compilerResults);
			return compilerResults.CompiledAssembly;
		}
示例#4
0
        public static CompilerResults CompileScript(string Source, string Reference, CodeDomProvider Provider)
        {
            ICodeCompiler compiler = Provider.CreateCompiler();
            CompilerParameters parms = new CompilerParameters();
            CompilerResults results;

            // Configure parameters
            parms.GenerateExecutable = false;
            parms.GenerateInMemory = true;
            parms.IncludeDebugInformation = false;
            if (Reference != null && Reference.Length != 0)
                parms.ReferencedAssemblies.Add(Reference);
            parms.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parms.ReferencedAssemblies.Add("System.dll");

            // Compile
            results = compiler.CompileAssemblyFromSource(parms, Source);

            return results;
        }
		/// <summary>Check code with given CodeDomProvider.</summary>
		/// <example>
		/// 	<code lang="CS" description="The following example gets some code and check it with given CodeDomProvider">
		/// string code = "double Calc(double x)
		/// {
		///     double gain = 1.5;
		///     return x*gain;
		/// }
		/// "
		/// String resultString;
		///  
		/// CodeExpressionChecker.CheckCode(new CSharpCodeProvider(), code, ref resultString);
		/// </code>
		/// </example>
		public static void CheckCode(CodeDomProvider provider, String sourceCode, ref String errorString)
		{
			ICodeCompiler compiler = provider.CreateCompiler();

			CompilerParameters cp = new CompilerParameters(new string[]{"mscorlib.dll", typeof(Point2D).Assembly.Location});
			cp.GenerateInMemory = true;       
			CompilerResults cr = compiler.CompileAssemblyFromSource(cp, sourceCode);
			if (cr.NativeCompilerReturnValue != 0)
			{
				int i = resultSpace;
				string outputString = "";

				while(i < cr.Output.Count)
				{
					outputString += cr.Output[i] + Environment.NewLine;
					i++;
				}
				// Return the results of compilation with error flag and error string
				errorString = outputString;
			}
			else
				errorString = "";
		}
        /// <summary>
        /// This overrides the CodeDomTest Run method that does verification
        /// on the tree provided in the BuildTree method you provide.
        /// </summary>
        /// <param name="provider">Provider to test.</param>
        /// <returns>True if the tree builds, compiles, searches and passes
        /// assembly verification.  False if any of these fails.</returns>
        public override bool Run (CodeDomProvider provider) {
            bool fail = false;

            // build the tree
            LogMessageIndent ();
            LogMessage ("- Generating tree.");
            CodeCompileUnit cu = new CodeCompileUnit ();
            LogMessageIndent ();
            BuildTree (provider, cu);
            LogMessageUnindent ();

            // validate tree using 'experimental' subset tester
            // but only if the test believes its in the subset
            if ((TestType & TestTypes.Subset) != 0) {
                SubsetConformance subsConf = new SubsetConformance ();
                LogMessage ("- Checking tree subset conformance.");
                if (!subsConf.ValidateCodeCompileUnit (cu))
                    LogMessage ("Failed subset tester: {0}",
                            subsConf.ToString ());
            }

            // realize source
            StringWriter sw = new StringWriter (CultureInfo.InvariantCulture);
#if WHIDBEY
            provider.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#else
            ICodeGenerator generator = provider.CreateGenerator ();
            generator.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#endif

            // only continue if the source could be realized into a string.
            if (!fail) {
                string source = sw.ToString ();

                if (saveSourceFileName.Length > 0) {
                    LogMessage ("- Saving source into '" + saveSourceFileName + "'");

                    // save this source to a file
                    DumpStringToFile (source, saveSourceFileName);
                }

                // log the source code
                //LogMessage (source);

                // search the source if the test case asks us to
                if (ShouldSearch) {
                    LogMessageIndent ();
                    Search (provider, source);
                    LogMessageUnindent ();
                }
                
                // continue only if the test case wants to compile or verify
                if (ShouldCompile || ShouldVerify) {

                    // ask the test case which compiler parameters it would like to use
                    CompilerParameters parms = GetCompilerParameters (provider);

#if FSHARP
                    // If the generated code has entrypoint, then F# requires us to generate EXE
                    bool hasEntryPoint = false;
                    foreach(CodeNamespace ns in cu.Namespaces)
                        foreach (CodeTypeDeclaration ty in ns.Types)
                            foreach(CodeTypeMember mem in ty.Members)
                                if (mem is CodeEntryPointMethod) { hasEntryPoint = true; }

                    // If the output file name is specified then it should be EXE
                    if (hasEntryPoint && parms.GenerateExecutable == false)
                    {
                        parms.GenerateExecutable = true;
                        if (saveAssemblyFileName.ToLower().EndsWith(".dll"))
                            saveAssemblyFileName = saveAssemblyFileName.Substring(0, saveAssemblyFileName.Length - 4) + ".exe";
                    }
#endif
                    
                    // add the appropriate compiler parameters if the user asked us
                    // to save assemblies to file
                    if (saveAssemblyFileName.Length > 0) {
                        parms.OutputAssembly = saveAssemblyFileName;
                        LogMessage ("- Compiling to '" + saveAssemblyFileName + "'.");
                    }

                    // always generate in memory for verification purposes
                    parms.GenerateInMemory = true;

                    // compile!
#if WHIDBEY
                    CompilerResults results = provider.CompileAssemblyFromDom (parms, cu);
#else
                    ICodeCompiler compiler = provider.CreateCompiler ();
                    CompilerResults results = compiler.CompileAssemblyFromDom (parms, cu);
#endif

                    if (results.NativeCompilerReturnValue != 0) {
                        // compilation failed
                        fail = true;
                        LogMessage ("- Compilation failed.");
                        
                        // log the compilation failed output
                        foreach (string msg in results.Output)
                            LogMessage (msg);

                    } else if (ShouldVerify) {
                        // compilation suceeded and we are asked to verify the
                        // compiled assembly
                        LogMessage ("- Verifying assembly.");

                        // verify the compiled assembly if it's there
                        if (results.CompiledAssembly != null) {
                            LogMessageIndent ();
                            VerifyAssembly (provider, results.CompiledAssembly);
                            LogMessageUnindent ();
                        }
                    }
                }
            }

            if (fail || !AreAllValidated ()) {
                // one of the steps above failed or a scenario was not
                // verified within the test case
                fail = true;
                LogMessage ("! Test '" + Name + "' failed.");

                // output failing scenarios
                if (!AreAllValidated()) {
                    LogMessage ("! Failing scenarios:");
                    foreach (Scenario s in GetNotValidated())
                    {
                        LogMessage ("-  " + s.ToString());
                    }
                }
            } else {
                // test passed
                LogMessage ("* Test '" + Name + "' passed.");
            }
            LogMessageUnindent ();

            // return true on success, false on failure
            return !fail;
        }
示例#7
0
 public CompilerInfo(CodeDomProvider provider)
 {
     Compiler = provider.CreateCompiler();
     CodeGen = provider.CreateGenerator();
 }
示例#8
0
        ///<remarks>Brendan Ingram has greatly improved this method.</remarks>		
        private static object LoadClass(CodeDomProvider codeProvider, string targetClassName, string source, bool sourceIsString)
        {
            CompilerParameters compilerParameters = new CompilerParameters();
            compilerParameters.GenerateExecutable = false;
            compilerParameters.GenerateInMemory = true;
            compilerParameters.IncludeDebugInformation = true;
            compilerParameters.TreatWarningsAsErrors = false;

            // Add the reference to the NxBRE.dll assembly.
            if ((ReferenceLinkMode == ReferenceLinkModes.NxBRE) || (ReferenceLinkMode == ReferenceLinkModes.Full))
                AddReferencedAssembly(compilerParameters, NxbreAssemblyLocation);

            // Add all implicitly referenced assemblies
            if ((ReferenceLinkMode == ReferenceLinkModes.CurrentDomain) || (ReferenceLinkMode == ReferenceLinkModes.Full))
                foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                    // do not add AssemblyBuilders (bug 1482753), thanks to Bob Brumfield
                    if (!(assembly is AssemblyBuilder))
                        AddReferencedAssembly(compilerParameters, assembly.Location);

            ICodeCompiler compiler = codeProvider.CreateCompiler();
            CompilerResults cr;

            if (sourceIsString)
                cr = compiler.CompileAssemblyFromSource(compilerParameters, source);
            else
                cr = compiler.CompileAssemblyFromFile(compilerParameters, source);

            if (cr.Errors.Count == 0)
                return cr.CompiledAssembly.CreateInstance(targetClassName);
            else
                throw new BREException(GetCompilerErrors(cr));
        }
示例#9
0
        private void CompileAssembly(CodeDomProvider provider, Hashtable typeDecls, string nsName) {
            nsName = "Microsoft.Xslt.CompiledScripts." + nsName;
            CodeNamespace msXslt = new CodeNamespace(nsName);            

            // Add all the default namespaces
            foreach(string ns in _defaultNamespaces) {
                msXslt.Imports.Add(new CodeNamespaceImport(ns));
            }

            foreach(CodeTypeDeclaration scriptClass in typeDecls.Values) {
                msXslt.Types.Add(scriptClass);
            }

            CodeCompileUnit unit = new CodeCompileUnit(); {
                unit.Namespaces.Add(msXslt);
                // This settings have sense for Visual Basic only. 
                // We can consider in future to allow user set them in <xsl:script option="???"> attribute.
                unit.UserData["AllowLateBound"]             = true;  // Allow variables to be undeclared
                unit.UserData["RequireVariableDeclaration"] = false; // Allow variables to be declared untyped
            }
            CompilerParameters compilParams = new CompilerParameters(); {
                compilParams.GenerateInMemory = true;
                compilParams.ReferencedAssemblies.Add(typeof(XPathNavigator).Module.FullyQualifiedName);
                compilParams.ReferencedAssemblies.Add("system.dll");
//                compilParams.ReferencedAssemblies.Add("microsoft.visualbasic.dll"); This is not requied somehow.
            }
            CompilerResults results = provider.CreateCompiler().CompileAssemblyFromDom(compilParams, unit);
            if (results.Errors.HasErrors) {
                StringWriter stringWriter = new StringWriter();
                foreach (CompilerError e in results.Errors) {
                    stringWriter.WriteLine(e.ToString());
                }
                System.Diagnostics.Debug.WriteLine(stringWriter.ToString());
                throw new XsltException(Res.Xslt_ScriptCompileErrors, stringWriter.ToString());
            }
            Assembly assembly = results.CompiledAssembly;
            foreach(DictionaryEntry entry in typeDecls) {
                string ns = (string)entry.Key;
                CodeTypeDeclaration scriptClass = (CodeTypeDeclaration)entry.Value;
                this.stylesheet.ScriptObjectTypes.Add(ns, assembly.GetType(nsName + "." + scriptClass.Name));
            }
        }
示例#10
0
        /// <summary>
        /// Function to compile .Net C#/VB source codes at runtime
        /// </summary>
        /// <param name="_CodeProvider">Base class for compiler provider</param>
        /// <param name="_SourceCode">C# or VB source code as a string</param>
        /// <param name="_SourceFile">External file containing C# or VB source code</param>
        /// <param name="_ExeFile">File path to create external executable file</param>
        /// <param name="_AssemblyName">File path to create external assembly file</param>
        /// <param name="_ResourceFiles">Required resource files to compile the code</param>
        /// <param name="_Errors">String variable to store any errors occurred during the process</param>
        /// <returns>Return TRUE if successfully compiled the code, else return FALSE</returns>
        private bool CompileCode(System.CodeDom.Compiler.CodeDomProvider _CodeProvider, string _SourceCode, string _SourceFile, string _ExeFile, string _AssemblyName, string[] _ResourceFiles, ref string _Errors)
        {
            // set interface for compilation
            System.CodeDom.Compiler.ICodeCompiler _CodeCompiler = _CodeProvider.CreateCompiler();

            // Define parameters to invoke a compiler
            System.CodeDom.Compiler.CompilerParameters _CompilerParameters =
                new System.CodeDom.Compiler.CompilerParameters();

            if (_ExeFile != null)
            {
                // Set the assembly file name to generate.
                _CompilerParameters.OutputAssembly = _ExeFile;

                // Generate an executable instead of a class library.
                _CompilerParameters.GenerateExecutable = true;
                _CompilerParameters.GenerateInMemory   = false; // Esto será lo que haya que cambiar para que se cargue en memoria
            }
            else if (_AssemblyName != null)
            {
                // Set the assembly file name to generate.
                _CompilerParameters.OutputAssembly = _AssemblyName;

                // Generate an executable instead of a class library.
                _CompilerParameters.GenerateExecutable = false;
                _CompilerParameters.GenerateInMemory   = false;
            }
            else
            {
                // Generate an executable instead of a class library.
                _CompilerParameters.GenerateExecutable = false;
                _CompilerParameters.GenerateInMemory   = true;
            }


            // Generate debug information.
            //_CompilerParameters.IncludeDebugInformation = true;

            // Set the level at which the compiler
            // should start displaying warnings.
            _CompilerParameters.WarningLevel = 3;

            // Set whether to treat all warnings as errors.
            _CompilerParameters.TreatWarningsAsErrors = false;

            // Set compiler argument to optimize output.
            _CompilerParameters.CompilerOptions = "/optimize";

            // Set a temporary files collection.
            // The TempFileCollection stores the temporary files
            // generated during a build in the current directory,
            // and does not delete them after compilation.
            _CompilerParameters.TempFiles = new System.CodeDom.Compiler.TempFileCollection(".", true);

            if (_ResourceFiles != null && _ResourceFiles.Length > 0)
            {
                foreach (string _ResourceFile in _ResourceFiles)
                {
                    // Set the embedded resource file of the assembly.
                    _CompilerParameters.EmbeddedResources.Add(_ResourceFile);
                }
            }


            try
            {
                // Invoke compilation
                System.CodeDom.Compiler.CompilerResults _CompilerResults = null;

                if (_SourceFile != null && System.IO.File.Exists(_SourceFile))
                {
                    // soruce code in external file
                    _CompilerResults = _CodeCompiler.CompileAssemblyFromFile(_CompilerParameters, _SourceFile);
                }
                else
                {
                    // source code pass as a string
                    _CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, _SourceCode);
                }

                if (_CompilerResults.Errors.Count > 0)
                {
                    // Return compilation errors
                    _Errors = "";
                    foreach (System.CodeDom.Compiler.CompilerError CompErr in _CompilerResults.Errors)
                    {
                        _Errors += "Line number " + CompErr.Line +
                                   ", Error Number: " + CompErr.ErrorNumber +
                                   ", '" + CompErr.ErrorText + ";\r\n\r\n";
                    }

                    // Return the results of compilation - Failed
                    return(false);
                }
                else
                {
                    // no compile errors
                    _Errors = null;
                }
            }
            catch (Exception _Exception)
            {
                // Error occurred when trying to compile the code
                _Errors = _Exception.Message;
                return(false);
            }

            // Return the results of compilation - Success
            return(true);
        }
示例#11
0
		public static CompilerResults CompileScript(
			string sSource, string sReference, string sAssembly,
			CodeDomProvider pProvider)
		{
			ICodeCompiler pCompiler = pProvider.CreateCompiler();
			CompilerParameters pParams = new CompilerParameters();
			
			// configure parameters
			pParams.GenerateExecutable = false;
			pParams.GenerateInMemory = false;
			pParams.OutputAssembly = sAssembly + ".dll";
			pParams.IncludeDebugInformation = false;
			if (sReference != null && sReference.Length != 0)
			{
				pParams.ReferencedAssemblies.Add(sReference);
			}
			pParams.ReferencedAssemblies.Add("System.dll");
			pParams.ReferencedAssemblies.Add("System.Drawing.dll");
			
			// compile
			return pCompiler.CompileAssemblyFromSource(pParams, sSource);
		}
示例#12
0
		///<remarks>Brendan Ingram has greatly improved this method.</remarks>		
		private static object LoadClass(CodeDomProvider codeProvider, string targetClassName, string source, bool sourceIsString) {
			if (compilerParameters == null) {
				compilerParameters = new CompilerParameters();
				compilerParameters.GenerateExecutable = false;
				compilerParameters.GenerateInMemory = true;
				compilerParameters.IncludeDebugInformation = true;
				compilerParameters.TreatWarningsAsErrors = false;
				
				// Add the referent to the NxBRE.dll assembly.
				compilerParameters.ReferencedAssemblies.Add(NxbreAssemblyLocation);
			
				// Add all implicitly referenced assemblies
				foreach(Assembly assy in AppDomain.CurrentDomain.GetAssemblies())
				{
					try
					{
						compilerParameters.ReferencedAssemblies.Add(assy.Location);
					}
					catch {}
				}
			}
			
			ICodeCompiler compiler = codeProvider.CreateCompiler();
			CompilerResults cr;
			
			if (sourceIsString)
				cr = compiler.CompileAssemblyFromSource(compilerParameters, source);
			else
				cr = compiler.CompileAssemblyFromFile(compilerParameters, source);
			
			if (cr.Errors.Count == 0)
				return cr.CompiledAssembly.CreateInstance(targetClassName);
			else
				throw new BREException(GetCompilerErrors(cr));
		}
 public void ToAssemblyFile(CodeCompileUnit compileunit, CodeDomProvider provider, string fileName)
 {
     #if NET2
     CompilerParameters cp = new CompilerParameters();
     cp.ReferencedAssemblies.Add("System.dll");
     cp.GenerateInMemory = false;
     cp.OutputAssembly = fileName;
     CompilerResults cr = provider.CompileAssemblyFromDom(cp, compileunit);
     #else
     ICodeCompiler compiler = provider.CreateCompiler();
     CompilerParameters cp = new CompilerParameters();
     cp.ReferencedAssemblies.Add( "System.dll" );
     cp.GenerateInMemory = false;
     cp.OutputAssembly = fileName;
      			CompilerResults cr = compiler.CompileAssemblyFromDom(cp, compileunit);
     #endif
 }
        public CompilerResults ToCompilerResults(CodeCompileUnit compileunit, CodeDomProvider provider, IDomainMap domainMap)
        {
            #if NET2
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.GenerateInMemory = true;

            string code = ToCode(compileunit, provider, domainMap);

            return provider.CompileAssemblyFromSource(cp, code);
            #else
            ICodeCompiler compiler = provider.CreateCompiler();
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add( "System.dll" );
            cp.GenerateInMemory = true;

            string code = ToCode(compileunit, provider, domainMap);

            return compiler.CompileAssemblyFromSource(cp, code);
            #endif
        }
		public virtual Type GetCompiledType () 
		{
			Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
			if (type != null)
				return type;

			Init ();
			string lang = parser.Language;
			CompilationConfiguration config;

			config = CompilationConfiguration.GetInstance (parser.Context);
			provider = config.GetProvider (lang);
			if (provider == null)
				throw new HttpException ("Configuration error. Language not supported: " +
							  lang, 500);

			compiler = provider.CreateCompiler ();

			CreateMethods ();
			compilerParameters.IncludeDebugInformation = parser.Debug;
			compilerParameters.CompilerOptions = config.GetCompilerOptions (lang) + " " +
							     parser.CompilerOptions;

			compilerParameters.WarningLevel = config.GetWarningLevel (lang);
			bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
			if (!Directory.Exists (dynamicBase))
				Directory.CreateDirectory (dynamicBase);

			TempFileCollection tempcoll = new TempFileCollection (config.TempDirectory, keepFiles);
			compilerParameters.TempFiles = tempcoll;
			string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
			compilerParameters.OutputAssembly = Path.Combine (dynamicBase, dllfilename);

			CompilerResults results = CachingCompiler.Compile (this);
			CheckCompilerErrors (results);
			Assembly assembly = results.CompiledAssembly;
			if (assembly == null) {
				if (!File.Exists (compilerParameters.OutputAssembly))
					throw new CompilationException (parser.InputFile, results.Errors,
						"No assembly returned after compilation!?");

				assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
			}

			results.TempFiles.Delete ();
			return assembly.GetType (mainClassExpr.Type.BaseType, true);
		}