예제 #1
0
        public string DoCompilation(string code, string name)
        {
            CodeDomProvider    provider   = CodeDomProvider.CreateProvider("C#");
            ICodeCompiler      compiler   = provider.CreateCompiler();
            CompilerParameters parameters = new CompilerParameters();

            parameters.OutputAssembly     = @name;
            parameters.GenerateExecutable = true;
            CompilerResults results = compiler.CompileAssemblyFromSource(parameters, code);

            System.Threading.Thread.Sleep(10000);

            if (results.Output.Count == 0)
            {
                return("success");
            }
            else
            {
                CompilerErrorCollection CErros = results.Errors;
                foreach (CompilerError err in CErros)
                {
                    string msg = string.Format("Erro:{0} on line{1} file name:{2}", err.Line, err.ErrorText, err.FileName);

                    return(msg);
                }
            }
            return("not working");
        }
예제 #2
0
        /// <summary>
        /// スクリプトをコンパイルする
        /// </summary>
        /// <exception cref="CompileErrorException">
        /// コンパイルエラーが発生した場合はこの例外を投げる
        /// </exception>
        public void Compile()
        {
            ICodeCompiler compiler = provider.CreateCompiler();

            CompilerParameters compilerParams = new CompilerParameters();

            foreach (string assembly in referenceAssemblies)
            {
                compilerParams.ReferencedAssemblies.Add(assembly);
            }
            compilerParams.GenerateInMemory        = true;
            compilerParams.GenerateExecutable      = false;
            compilerParams.IncludeDebugInformation = generateDebugInfo;

            CompilerResults result = compiler.CompileAssemblyFromSourceBatch
                                         (compilerParams, (string[])scriptCode.ToArray(typeof(string)));

            foreach (CompilerError error in result.Errors)
            {
                if (!error.IsWarning)
                {
                    throw new CodeDomCompileErrorException(result);
                }
            }

            scriptAssembly = result.CompiledAssembly;
        }
예제 #3
0
        public object Eval(CodeDomProvider cdp, string scriptCode)
        {
            ICodeCompiler      cc   = cdp.CreateCompiler();
            CompilerParameters args = new CompilerParameters();

            args.GenerateExecutable = false;
            args.GenerateInMemory   = true;
            foreach (string s in ReferencedAssemblies)
            {
                args.ReferencedAssemblies.Add(s);
            }
            args.CompilerOptions = CompilerOptions;
            fileCount++;
            string          guidStr      = Guid.NewGuid().ToString("N");
            string          assemblyName = "DynamicAssembly" + guidStr;
            string          className    = "DynamicClass" + guidStr;
            CompilerResults res          = cc.CompileAssemblyFromSource(args, templateCode.Replace("#ASSEMBLYNAME#", assemblyName).Replace("#CLASSNAME#", className).Replace("#SCRIPTCODE#", scriptCode));

            Results.Clear();
            foreach (string s in res.Output)
            {
                Results.Add(s);
            }
            if (res.Output.Count > 0)
            {
                return(null);
            }
            return(res.CompiledAssembly.CreateInstance(assemblyName + "." + className));
        }
예제 #4
0
        /// <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 = "";
            }
        }
예제 #5
0
            public CompilerInfo(LanguageId languageId, CodeDomProvider provider)
            {
                _lang = languageId;

                Compiler = provider.CreateCompiler();
                CodeGen  = provider.CreateGenerator();
            }
예제 #6
0
        public static CompilerResults Compile(string source, string assembly, CodeDomProvider provider)
        {
            ICodeCompiler      compiler = provider.CreateCompiler();
            CompilerParameters parms    = new CompilerParameters();
            CompilerResults    results;

            // Configure parameters
            parms.GenerateExecutable      = false;
            parms.GenerateInMemory        = true;
            parms.IncludeDebugInformation = false;
            parms.ReferencedAssemblies.AddRange(new string[] {
                "System.dll",
                "System.Data.dll",
                "System.Drawing.dll",
                "System.Windows.Forms.dll",
                "control.dll",
                "pluginfo.dll"
            });

            string dir = System.Windows.Forms.Application.StartupPath + @"\plugins\";

            System.IO.Directory.CreateDirectory(dir + assembly);
            parms.OutputAssembly = dir + assembly + @"\" + assembly + ".dll";

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

            return(results);
        }
예제 #7
0
        /// <summary>
        /// Returns the results of the compilation
        /// </summary>
        /// <param name="Source"></param>
        /// <param name="Reference"></param>
        /// <param name="Provider"></param>
        /// <returns></returns>
        public static CompilerResults CompileScript(string Source, string Reference, CodeDomProvider Provider)
        {
            ICodeCompiler      compiler = Provider.CreateCompiler();
            CompilerParameters parms    = new CompilerParameters();
            CompilerResults    results;

            // Configure parameters
            parms.MainClass          = "Script";
            parms.GenerateExecutable = false;
            parms.GenerateInMemory   = true;
            parms.TempFiles          = new TempFileCollection(Path.GetTempPath(), false);
            //parms.OutputAssembly="scripter_"+Assembly.GetCallingAssembly().GetName().Version.Build;
            parms.IncludeDebugInformation = false;
            if (Reference != null && Reference.Length != 0)
            {
                parms.ReferencedAssemblies.Add(Reference);
            }
            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                parms.ReferencedAssemblies.Add(asm.Location);
            }
            parms.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parms.ReferencedAssemblies.Add("System.dll");

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

            return(results);
        }
예제 #8
0
        public object LoadCode(CodeDomProvider cdp, string scriptCode, string assemblyName, string className)
        {
            ICodeCompiler      cc   = cdp.CreateCompiler();
            CompilerParameters args = new CompilerParameters();

            args.GenerateExecutable = false;
            args.GenerateInMemory   = true;
            foreach (string s in ReferencedAssemblies)
            {
                args.ReferencedAssemblies.Add(s);
            }
            args.CompilerOptions = CompilerOptions;
            CompilerResults res = cc.CompileAssemblyFromSource(args, scriptCode);

            Results.Clear();
            foreach (string s in res.Output)
            {
                Results.Add(s);
            }
            if (res.Output.Count > 0)
            {
                return(null);
            }
            return(res.CompiledAssembly.CreateInstance(assemblyName + "." + className));
        }
예제 #9
0
        public virtual Type GetScriptClass(string code, string classSuffix, XPathNavigator scriptNode, Evidence evidence)
        {
            PermissionSet ps = SecurityManager.ResolvePolicy(evidence);

            if (ps != null)
            {
                ps.Demand();
            }

            ICodeCompiler      compiler   = CodeDomProvider.CreateCompiler();
            CompilerParameters parameters = new CompilerParameters();

            parameters.CompilerOptions = DefaultCompilerOptions;

            // get source filename
            string filename = String.Empty;

            try {
                if (scriptNode.BaseURI != String.Empty)
                {
                    filename = new Uri(scriptNode.BaseURI).LocalPath;
                }
            } catch (FormatException) {
            }
            if (filename == String.Empty)
            {
                filename = "__baseURI_not_supplied__";
            }

            // get source location
            IXmlLineInfo li = scriptNode as IXmlLineInfo;

            string source = SourceTemplate.Replace("{0}",
                                                   DateTime.Now.ToString(CultureInfo.InvariantCulture))
                            .Replace("{1}", classSuffix)
                            .Replace("{2}", code);

            source = FormatSource(li, filename, source);

            CompilerResults res = compiler.CompileAssemblyFromSource(parameters, source);

            foreach (CompilerError err in res.Errors)
            {
                if (!err.IsWarning)
                {
                    // Actually it should be
                    // XsltCompileException, but to match
                    // with silly MS implementation...
//					throw new XsltCompileException ("Stylesheet script compile error: \n" + FormatErrorMessage (res) /*+ "Code :\n" + source*/, null, scriptNode);
                    throw new XsltException("Stylesheet script compile error: \n" + FormatErrorMessage(res) /*+ "Code :\n" + source*/, null, scriptNode);
                }
            }

            if (res.CompiledAssembly == null)
            {
                throw new XsltCompileException("Cannot compile stylesheet script", null, scriptNode);
            }
            return(res.CompiledAssembly.GetType("GeneratedAssembly.Script" + classSuffix));
        }
예제 #10
0
        /// <include file='doc\BaseCompiler.uex' path='docs/doc[@for="BaseCompiler.GetCompiledType"]/*' />
        /// <devdoc>
        ///
        /// </devdoc>
        protected Type GetCompiledType()
        {
            // Instantiate an ICompiler based on the language
            CodeDomProvider codeProvider = (CodeDomProvider)HttpRuntime.CreatePublicInstance(
                CompilerInfo.CompilerType);
            ICodeCompiler compiler = codeProvider.CreateCompiler();

            _generator = codeProvider.CreateGenerator();

            _stringResourceBuilder = new StringResourceBuilder();

            // Build the data tree that needs to be compiled
            BuildSourceDataTree();

            // Create the resource file if needed
            if (_stringResourceBuilder.HasStrings)
            {
                string resFileName = _compilParams.TempFiles.AddExtension("res");
                _stringResourceBuilder.CreateResourceFile(resFileName);
                CompilParams.Win32Resource = resFileName;
            }

            // Compile into an assembly
            CompilerResults results;

            try {
                results = codeProvider.CreateCompiler().CompileAssemblyFromDom(_compilParams, _sourceData);
            }
            catch (Exception e) {
                throw new HttpUnhandledException(HttpRuntime.FormatResourceString(SR.CompilationUnhandledException, codeProvider.GetType().FullName), e);
            }

            string fullTypeName = _sourceDataNamespace.Name + "." + _sourceDataClass.Name;

            ThrowIfCompilerErrors(results, codeProvider, _sourceData, null, null);

            // After the compilation, update the list of assembly dependencies to be what
            // the assembly actually needs.
            Parser.AssemblyDependencies = Util.GetReferencedAssembliesHashtable(
                results.CompiledAssembly);

            // Get the type from the assembly
            return(results.CompiledAssembly.GetType(fullTypeName, true /*throwOnFail*/));
        }
예제 #11
0
        private static CompilerResults CompileCode(CodeDomProvider provider, string Codes, string filepath)
        {
            ICodeCompiler      compiler = provider.CreateCompiler();
            CompilerParameters cp       = new CompilerParameters(new string[] { "System.dll" }, filepath, false);

            cp.GenerateExecutable = true;
            CompilerResults cr = compiler.CompileAssemblyFromSource(cp, Codes);

            return(cr);
        }
예제 #12
0
        ICodeCompiler CreateCodeDomCompiler(ScriptingLanguage lang)
        {
            CodeDomProvider provider = (
                lang == ScriptingLanguage.JScript     ? (CodeDomProvider)Activator.CreateInstance(Type.GetType("Microsoft.JScript.JScriptCodeProvider, " + AssemblyRef.MicrosoftJScript), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null) :
                lang == ScriptingLanguage.VisualBasic ? (CodeDomProvider) new Microsoft.VisualBasic.VBCodeProvider() :
                /*CSharp | default */ (CodeDomProvider) new Microsoft.CSharp.CSharpCodeProvider()
                );

            return(provider.CreateCompiler());
        }
예제 #13
0
        public static bool BuildCode(string Code, string OutputPath, CodeDomProvider Provider, string References = "none")
        {
            ICodeCompiler      Compiler   = Provider.CreateCompiler();
            CompilerParameters Parameters = new CompilerParameters();

            Parameters.GenerateExecutable = false;
            Parameters.OutputAssembly     = OutputPath;

            foreach (Assembly Asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                Parameters.ReferencedAssemblies.Add(Asm.Location);
            }


            if (!(References == "none"))
            {
                string[] Files = References.Split(';');

                foreach (string f in Files)
                {
                    if (System.IO.File.Exists(f))
                    {
                        Parameters.ReferencedAssemblies.Add(f);
                        Debug.Logs.Write("[Plugin.Builder] Add reférence : '" + f.Split('\\').Last() + "'", Debug.LogType.Info);
                    }
                }
            }

            CompilerResults result = Compiler.CompileAssemblyFromSource(Parameters, Code);

            if (result.Errors.Count > 0)
            {
                Debug.Logs.Write("[Plugin.Builder] Compilation failled! '" + OutputPath + "' with (" + result.Errors.Count + " Error)", Debug.LogType.Errore);

                foreach (CompilerError Error in result.Errors)
                {
                    if (Error.IsWarning)
                    {
                        Debug.Logs.Write("   Ln" + Error.Line + " '" + Error.ErrorText + "'", Debug.LogType.Warning);
                    }
                    else
                    {
                        Debug.Logs.Write("    Ln" + Error.Line + " '" + Error.ErrorText + "'", Debug.LogType.Errore);
                    }
                }


                return(false);
            }
            else
            {
                Debug.Logs.Write("[Plugin.Builder] Compilation success! '" + OutputPath + "'", Debug.LogType.Info);
                return(true);
            }
        }
예제 #14
0
파일: compiler.cs 프로젝트: ydunk/masters
        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));
            }
        }
예제 #15
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));
            }
        }
예제 #16
0
        //////////////////////Компилируем//////////////////////////////////////////////
        public static CompilerResults COMPILER_CODE_SERVER(CodeDomProvider provider,
                                                           String sourceFile,
                                                           String exeFile)
        {
            ICodeCompiler compiler = provider.CreateCompiler();

            String []          referenceAssemblies = { "System.dll" };
            CompilerParameters cp = new CompilerParameters(referenceAssemblies,
                                                           exeFile, false);

            cp.GenerateExecutable = true;
            CompilerResults cr = compiler.CompileAssemblyFromFile(cp, sourceFile);

            return(cr);
        }
예제 #17
0
        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 static void CompileFiles(string assemblyFName, string[] references, string[] files)
        {
            using (CodeDomProvider provider = GetCSharpCodeDomProvider())
            {
                CompilerParameters parameters = CreateDefaultCompilerParameters();
                parameters.IncludeDebugInformation = false;
                parameters.OutputAssembly          = assemblyFName;
                parameters.GenerateExecutable      = ".exe" == Path.GetExtension(assemblyFName).ToLower();
                parameters.ReferencedAssemblies.AddRange(references);

                ICodeCompiler   compiler = provider.CreateCompiler();
                CompilerResults results  = compiler.CompileAssemblyFromFileBatch(parameters, files);
                if (ContainsErrors(results.Errors))
                {
                    throw new ApplicationException(GetErrorString(results.Errors));
                }
            }
        }
예제 #19
0
        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
        }
예제 #20
0
        public void Compilation_NotSupported()
        {
            CodeDomProvider provider = GetProvider();

            var options = new CompilerParameters(new string[] { }, "test.exe");

            var cu = new CodeCompileUnit();
            var ns = new CodeNamespace("ns");
            var cd = new CodeTypeDeclaration("Program");
            var mm = new CodeEntryPointMethod();

            cd.Members.Add(mm);
            ns.Types.Add(cd);
            cu.Namespaces.Add(ns);

            string tempPath = Path.GetTempFileName();

            try
            {
                File.WriteAllText(tempPath, GetEmptyProgramSource());

                Assert.Throws <PlatformNotSupportedException>(() => provider.CompileAssemblyFromFile(options, tempPath));
                Assert.Throws <PlatformNotSupportedException>(() => provider.CompileAssemblyFromDom(options, cu));
                Assert.Throws <PlatformNotSupportedException>(() => provider.CompileAssemblyFromSource(options, GetEmptyProgramSource()));

#pragma warning disable 0618 // obsolete
                ICodeCompiler cc = provider.CreateCompiler();
                Assert.Throws <PlatformNotSupportedException>(() => cc.CompileAssemblyFromDom(options, cu));
                Assert.Throws <PlatformNotSupportedException>(() => cc.CompileAssemblyFromDomBatch(options, new[] { cu }));
                Assert.Throws <PlatformNotSupportedException>(() => cc.CompileAssemblyFromFile(options, tempPath));
                Assert.Throws <PlatformNotSupportedException>(() => cc.CompileAssemblyFromFileBatch(options, new[] { tempPath }));
                Assert.Throws <PlatformNotSupportedException>(() => cc.CompileAssemblyFromSource(options, GetEmptyProgramSource()));
                Assert.Throws <PlatformNotSupportedException>(() => cc.CompileAssemblyFromSourceBatch(options, new[] { GetEmptyProgramSource() }));
#pragma warning restore 0618
            }
            finally
            {
                File.Delete(tempPath);
            }
        }
예제 #21
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));
        }
예제 #22
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);
        }
예제 #23
0
 public CompilerInfo(CodeDomProvider provider)
 {
     Compiler = provider.CreateCompiler();
     CodeGen  = provider.CreateGenerator();
 }
예제 #24
0
        public virtual Type GetCompiledType()
        {
            Type type = CachingCompiler.GetTypeFromCache(parser.InputFile);

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

            ConstructType();
            string lang = parser.Language;
            string tempdir;
            string compilerOptions;
            int    warningLevel;

            Provider = CreateProvider(parser.Context, lang, out compilerOptions, out warningLevel, out tempdir);
            if (Provider == null)
            {
                throw new HttpException("Configuration error. Language not supported: " +
                                        lang, 500);
            }

#if !NET_2_0
            compiler = provider.CreateCompiler();
#endif

            CompilerParameters parameters = CompilerParameters;
            parameters.IncludeDebugInformation = parser.Debug;
            parameters.CompilerOptions         = compilerOptions + " " + parser.CompilerOptions;
            parameters.WarningLevel            = warningLevel;

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

            if (tempdir == null || tempdir == "")
            {
                tempdir = DynamicDir();
            }

            TempFileCollection tempcoll = new TempFileCollection(tempdir, keepFiles);
            parameters.TempFiles = tempcoll;
            string dllfilename = Path.GetFileName(tempcoll.AddExtension("dll", true));
            parameters.OutputAssembly = Path.Combine(DynamicDir(), dllfilename);

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

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

            results.TempFiles.Delete();
            Type mainClassType = assembly.GetType(MainClassType, true);

#if NET_2_0
            if (parser.IsPartial)
            {
                // With the partial classes, we need to make sure we
                // don't have any methods that should have not been
                // created (because they are accessible from the base
                // types). We cannot do this normally because the
                // codebehind file is actually a partial class and we
                // have no way of identifying the partial class' base
                // type until now.
                if (!isRebuilding && CheckPartialBaseType(mainClassType))
                {
                    isRebuilding = true;
                    parser.RootBuilder.ResetState();
                    return(GetCompiledType());
                }
            }
#endif

            return(mainClassType);
        }
예제 #25
0
        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);
                }
#if !NET_2_0
                ICodeCompiler compiler = provider.CreateCompiler();
#else
                CodeDomProvider compiler = provider;
#endif

                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);
        }
예제 #26
0
        /// <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);
        }
예제 #27
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);
        }
예제 #28
0
        public virtual Type GetScriptClass(string code, string classSuffix, XPathNavigator scriptNode, Evidence evidence)
        {
            PermissionSet ps = SecurityManager.ResolvePolicy(evidence);

            if (ps != null)
            {
                ps.Demand();
            }

            // The attempt to use an already pre-compiled
            // class assumes the caller has computed the
            // classSuffix as a hash of the code
            // string. MSXslScriptManager.cs does that.
            // The mechanism how exactly such pre-compiled
            // classes should be produced are not
            // specified here.
            string scriptname = "Script" + classSuffix;
            string typename   = "GeneratedAssembly." + scriptname;

            try
            {
                Type retval = Type.GetType(typename);
                if (retval != null)
                {
                    return(retval);
                }
            }
            catch
            {
            }

            try
            {
                Type retval = Assembly.LoadFrom(scriptname + ".dll").GetType(typename);
                if (retval != null)
                {
                    return(retval);
                }
            }
            catch
            {
            }

            // OK, we have to actually compile the script.
            ICodeCompiler      compiler   = CodeDomProvider.CreateCompiler();
            CompilerParameters parameters = new CompilerParameters();

            parameters.CompilerOptions = DefaultCompilerOptions;

            // get source filename
            string filename = String.Empty;

            try
            {
                if (scriptNode.BaseURI != String.Empty)
                {
                    filename = new Uri(scriptNode.BaseURI).LocalPath;
                }
            }
            catch (FormatException)
            {
            }
            if (filename == String.Empty)
            {
                filename = "__baseURI_not_supplied__";
            }

            // get source location
            IXmlLineInfo li = scriptNode as IXmlLineInfo;

            string source = SourceTemplate.Replace("{0}",
                                                   DateTime.Now.ToString(CultureInfo.InvariantCulture))
                            .Replace("{1}", classSuffix)
                            .Replace("{2}", code);

            source = FormatSource(li, filename, source);

            CompilerResults res = compiler.CompileAssemblyFromSource(parameters, source);

            foreach (CompilerError err in res.Errors)
            {
                if (!err.IsWarning)
                {
                    // Actually it should be
                    // XsltCompileException, but to match
                    // with silly MS implementation...
//					throw new XsltCompileException ("Stylesheet script compile error: \n" + FormatErrorMessage (res) /*+ "Code :\n" + source*/, null, scriptNode);
                    throw new XsltException("Stylesheet script compile error: \n" + FormatErrorMessage(res) /*+ "Code :\n" + source*/, null, scriptNode);
                }
            }

            if (res.CompiledAssembly == null)
            {
                throw new XsltCompileException("Cannot compile stylesheet script", null, scriptNode);
            }
            return(res.CompiledAssembly.GetType(typename));
        }
예제 #29
0
        private CompilerResults Compile(CodeDomProvider provider, string[] files)
        {
            ICodeCompiler compiler = provider.CreateCompiler();

            return(compiler.CompileAssemblyFromFileBatch(m_params, files));
        }