Beispiel #1
1
        public static Assembly Compile(string sSource, string[] referencedAssemblies)
        {
            Microsoft.CSharp.CSharpCodeProvider comp = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            if (!PlatformDetector.IsUnix)
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", ""));
            }
            else
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file://", ""));
            }
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            foreach (var assembly in referencedAssemblies)
            {

                cp.ReferencedAssemblies.Add(Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory
                    , assembly + ".dll"));
            }
            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sSource);
            if (cr.Errors.HasErrors)
            {
                StringBuilder sError = new StringBuilder();
                sError.Append("Error Compiling Expression: ");
                foreach (CompilerError err in cr.Errors)
                    sError.AppendFormat("{0}\n", err.ErrorText);
                throw new ApplicationException("Ошибка компиляции выражения: " + sError.ToString() + "\n" + sSource);
            }
            return cr.CompiledAssembly;
        }
Beispiel #2
0
        public override object Execute(string code)
        {
            ICodeCompiler      compiler  = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();
            CompilerParameters cmpParams = new System.CodeDom.Compiler.CompilerParameters();

            cmpParams.GenerateInMemory   = true;
            cmpParams.GenerateExecutable = true;
            //cmpParams.CompilerOptions = "/t:exe";

            foreach (string ass in this._referencedAssemblies)
            {
                cmpParams.ReferencedAssemblies.Add(ass + ".dll");
            }

            string codeString = this.GenerateReferenceString();

            codeString = this.InsertCode(code);

            CompilerResults results = compiler.CompileAssemblyFromSource(cmpParams, codeString);

//			foreach (System.CodeDom.Compiler.CompilerError ce in results.Errors)
//				this.Put(ce.ErrorText);

            if (results.Errors.Count == 0 && results.CompiledAssembly != null)
            {
                System.Reflection.MethodInfo methodInfo = results.CompiledAssembly.EntryPoint;
                return(methodInfo.Invoke(null, null));
            }
            return(null);
        }
Beispiel #3
0
        private static string CompileString(string csharpCode, string outFile)
        {
            var provider   = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters {
                OutputAssembly     = outFile,
                GenerateExecutable = false,
                GenerateInMemory   = false
            };

            parameters.ReferencedAssemblies.Add(typeof(ExportAttribute).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(IPythonInterpreterFactoryProvider).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(InterpreterConfiguration).Assembly.Location);
            var result = provider.CompileAssemblyFromSource(parameters, csharpCode);

            if (result.Errors.HasErrors)
            {
                foreach (var err in result.Errors)
                {
                    Console.WriteLine(err);
                }
            }

            if (!File.Exists(outFile))
            {
                Assert.Fail("Failed to compile {0}", outFile);
            }
            _tempFiles.Add(outFile);
            return(outFile);
        }
        //-----------------------------------------------------------------------------
        // Internal Methods
        //-----------------------------------------------------------------------------
        // Compile the final code for a script only to find any errors and/or warnings.
        private static ScriptCompileResult CompileScript(string code)
        {
            // Setup the compile options.
            CompilerParameters options	= new CompilerParameters();
            options.GenerateExecutable	= false; // We want a Dll (Class Library)
            options.GenerateInMemory	= true;

            // Add the assembly references.
            Assembly zeldaApiAssembly = Assembly.GetAssembly(typeof(ZeldaAPI.CustomScriptBase));
            options.ReferencedAssemblies.Add(zeldaApiAssembly.Location);

            // Create a C# code provider and compile the code.
            Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults csResult = csProvider.CompileAssemblyFromSource(options, code);

            // Copy warnings and errors into the ScriptComileResult.
            ScriptCompileResult result	= new ScriptCompileResult();
            foreach (CompilerError csError in csResult.Errors) {
                ScriptCompileError error = new ScriptCompileError(csError.Line,
                    csError.Column, csError.ErrorNumber, csError.ErrorText, csError.IsWarning);
                if (error.IsWarning)
                    result.Warnings.Add(error);
                else
                    result.Errors.Add(error);
            }

            return result;
        }
Beispiel #5
0
        public static Assembly Compile(string sSource, string[] referencedAssemblies)
        {
            Microsoft.CSharp.CSharpCodeProvider comp = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();

            if (!PlatformDetector.IsUnix)
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", ""));
            }
            else
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file://", ""));
            }
            cp.GenerateExecutable = false;
            cp.GenerateInMemory   = true;
            foreach (var assembly in referencedAssemblies)
            {
                cp.ReferencedAssemblies.Add(Path.Combine(
                                                AppDomain.CurrentDomain.BaseDirectory
                                                , assembly + ".dll"));
            }
            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sSource);

            if (cr.Errors.HasErrors)
            {
                StringBuilder sError = new StringBuilder();
                sError.Append("Error Compiling Expression: ");
                foreach (CompilerError err in cr.Errors)
                {
                    sError.AppendFormat("{0}\n", err.ErrorText);
                }
                throw new ApplicationException("Ошибка компиляции выражения: " + sError.ToString() + "\n" + sSource);
            }
            return(cr.CompiledAssembly);
        }
Beispiel #6
0
        // Emit byte code for the expression tree owned by this root.
        // Accepts the compiler parameters that were given to PieCodeProvider
        // since it will be needed for the CSharpCodeProvider.
        public CompilerResults Emit(CompilerParameters compilerParams, Root root)
        {
            // Emit the code compile unit, the top of the codedom tree.
            // This method will cal emit method for all child expressions
            // until all expressions have had byte code emitted.
            var codeCompileUnit = RootEmitter.Emit(root);

            // Create the C# compiler.
            var csProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BracingStyle = "C";

            // Compile the codedom tree into an assembly
            var sw = new StringWriter();

            csProvider.GenerateCodeFromCompileUnit(codeCompileUnit, sw, options);

            // Display the C# code for debugging purposes.
            string ccode = sw.GetStringBuilder().ToString();

            Console.WriteLine(ccode);

            // Get the results of the compilation: the assembly and error list
            CompilerResults results = csProvider.CompileAssemblyFromSource(compilerParams, ccode);

            // Store all C# compiler errors, so that they can be included with Pie compiler errors..
            foreach (CompilerError e in root.CompilerErrors)
            {
                results.Errors.Add(e);
            }
            root.CompilerErrors.Clear();

            return(results);
        }
Beispiel #7
0
        public void Compile()
        {
            if (isParsed)
            {
                string code = Code.Replace("insert it here", this.AddedCode).ToString();
                using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
                {
                    CompilerParameters parameters = new CompilerParameters();
                    parameters.GenerateExecutable = true;

                    parameters.OutputAssembly = Path.Combine(AssemblyFolder, AssemblyName);
                    var res = provider.CompileAssemblyFromSource(parameters, code);


                    foreach (var item in res.Errors)
                    {
                        Console.WriteLine(string.Format(CultureInfo.InvariantCulture, item.ToString()));
                    }
                    if (res.Errors.Count == 0)
                    {
                        Console.WriteLine("Successful compilaton");
                    }
                }
            }
        }
        public static string ParseString(string input)
        {
            var provider   = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateExecutable = false,
                GenerateInMemory   = true,
            };

            var code = @"
        namespace Tmp
        {
            public class TmpClass
            {
                public static string GetValue()
                {
                    return """ + input + @""";
                }
            }
        }";

            var compileResult = provider.CompileAssemblyFromSource(parameters, code);

            if (compileResult.Errors.HasErrors)
            {
                throw new ArgumentException(compileResult.Errors.Cast <System.CodeDom.Compiler.CompilerError>().First(e => !e.IsWarning).ErrorText);
            }

            var asmb   = compileResult.CompiledAssembly;
            var method = asmb.GetType("Tmp.TmpClass").GetMethod("GetValue");

            return(method.Invoke(null, null) as string);
        }
Beispiel #9
0
        // This version load the compiled assembly in the current domain => you can't unload it
        static public CompilerResults Compile(CompileParam cparam)
        {
            string[] dependencies = new string[] { "System.dll" };
            if (cparam.m_dependencies != null)
            {
                dependencies = cparam.m_dependencies;
            }

            System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();

            cp.GenerateExecutable      = false;
            cp.OutputAssembly          = cparam.m_outName;
            cp.IncludeDebugInformation = cparam.m_bDebug;
            foreach (string s in dependencies)
            {
                cp.ReferencedAssemblies.Add(s);
            }
            cp.GenerateInMemory      = false;
            cp.WarningLevel          = 3;
            cp.TreatWarningsAsErrors = false;
            cp.CompilerOptions       = "/optimize";

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, cparam.m_inSource);

            return(cr);
        }
        private static Assembly GenerateLameFacadeAssembly(string lameDllName)
        {
            // Get a modified source with proper DLL name
            // Should be good for .NET Framework 4.5 without any define constants.
            // Otherwise, add proper define(s) to the compiler options
            var thisAsm = typeof(Mp3LameAudioEncoder).Assembly;
            var source  = GetLameFacadeAssemblySource(lameDllName, thisAsm);

            // Compile it to a new in-memory assembly
            var compiler        = new Microsoft.CSharp.CSharpCodeProvider();
            var compilerOptions = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                CompilerOptions         = "/optimize",
                ReferencedAssemblies    = { "mscorlib.dll", thisAsm.Location }
            };
            var compilerResult = compiler.CompileAssemblyFromSource(compilerOptions, source);

            if (compilerResult.Errors.HasErrors)
            {
                throw new Exception("Could not generate LAME facade assembly.");
            }

            return(compilerResult.CompiledAssembly);
        }
Beispiel #11
0
        /// <summary>
        /// 编译指定脚本源码,返回编译结果
        /// </summary>
        /// <param name="source">源码</param>
        /// <param name="language">语言</param>
        /// <param name="outputFile">输出程序集文件</param>
        /// <returns>ScriptAgent的编译结果对象(永不为null)</returns>
        public CompileResults CompileScript(string source, ScriptLanguage language, string outputFile)
        {
            CodeDomProvider provider = null;

            switch (language)
            {
            case ScriptLanguage.VBNET:
                provider = new Microsoft.VisualBasic.VBCodeProvider();
                break;

            case ScriptLanguage.CSharp:
                provider = new Microsoft.CSharp.CSharpCodeProvider();
                break;
            }

            CompilerParameters param = this.GetCompilerParameters(outputFile);

            if (param == null)
            {
                return(new CompileResults());
            }
            string          szAssemblyDescriptor = this.GetScriptAssemblyDescriptor(language);
            CompilerResults results = null;

            try
            {
                source  = this.FormatScript(source, language);
                results = provider.CompileAssemblyFromSource(param, szAssemblyDescriptor, source);
            }
            catch (Exception ex)
            {
                LogManager.Instance.WriteLog("ScriptCompiler.CompileScript", ex);
            }
            return(this.GetCompileResults(results));
        }
        public static Assembly Compile(string sourcecode, string[] references, CompileLanguage language = CompileLanguage.CSharp)
        {
            CodeDomProvider comp = null;
            switch (language)
            {
                case CompileLanguage.VisualBasic:
                    comp = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                case CompileLanguage.CSharp:
                default:
                    comp = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
            }
            CompilerParameters cp = new CompilerParameters();
            foreach (string reference in references)
            {
                cp.ReferencedAssemblies.Add(reference);
            }
            cp.GenerateInMemory = true;

            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sourcecode);
            if (cr.Errors.HasErrors)
            {
                string error = string.Empty;
                foreach (CompilerError err in cr.Errors)
                {
                    error += err.ErrorText + System.Environment.NewLine;
                }
                System.Diagnostics.Trace.WriteLine(error);
                return null;
            }

            return cr.CompiledAssembly;
        }
Beispiel #13
0
        private void btnCompiler_Click(object sender, EventArgs e)
        {
            string        code = this.txtCode.Text;
            StringBuilder str  = new StringBuilder();

            Microsoft.CSharp.CSharpCodeProvider        codeProvider  = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters comparameters = new System.CodeDom.Compiler.CompilerParameters();
            comparameters.ReferencedAssemblies.Add("System.dll");
            comparameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            comparameters.GenerateInMemory = true;
            System.CodeDom.Compiler.CompilerResults res = codeProvider.CompileAssemblyFromSource(comparameters, code);
            if (res.Errors.HasErrors)
            {
                Console.WriteLine("编译错误:");
                foreach (System.CodeDom.Compiler.CompilerError err in res.Errors)
                {
                    str.AppendLine(@"/r/nLine:" +
                                   err.ErrorText);
                    // str.AppendLine(err.ErrorText);
                    // Console.WriteLine(err.ErrorText);
                }
            }
            else
            {
                object myClass = res.CompiledAssembly.CreateInstance("MyClass");
                var    result  = myClass.GetType().GetMethod("PrintConsole").Invoke(myClass, new object[] { "Hello World" });
                str.AppendLine(result.ToString());
            }
            this.txtResult.Text = str.ToString();
            //Console.Read();
        }
Beispiel #14
0
        public static T Create <T>(string code, string className, params string[] referencedAssemblies)
        {
            using (var csharp = new Microsoft.CSharp.CSharpCodeProvider())
            {
                var parameters = new System.CodeDom.Compiler.CompilerParameters()
                {
                    GenerateInMemory = true,
                };
                if (referencedAssemblies != null)
                {
                    parameters.ReferencedAssemblies.AddRange(referencedAssemblies);
                }
                var assemblyName = typeof(T).Assembly.GetName().Name + ".dll";
                if (typeof(T).Assembly != Assembly.GetExecutingAssembly() && (referencedAssemblies == null || !referencedAssemblies.Contains(assemblyName)))
                {
                    parameters.ReferencedAssemblies.Add(assemblyName);
                }

                var res = csharp.CompileAssemblyFromSource(parameters, code);
                if (res.Errors.HasErrors)
                {
                    var errors = string.Join("\n", res.Errors.OfType <CompilerError>().Select(r => r.ToString()));
                    throw new Exception(string.Format("Error compiling:\n{0}", errors));
                }

                return((T)res.CompiledAssembly.CreateInstance(className));
            }
        }
Beispiel #15
0
        public override object Execute(string code)
        {
            ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();
            CompilerParameters cmpParams = new System.CodeDom.Compiler.CompilerParameters();
            cmpParams.GenerateInMemory = true;
            cmpParams.GenerateExecutable = true;
            //cmpParams.CompilerOptions = "/t:exe";

            foreach (string ass in this._referencedAssemblies)
                cmpParams.ReferencedAssemblies.Add(ass+".dll");

            string codeString = this.GenerateReferenceString();
            codeString = this.InsertCode(code);

            CompilerResults results = compiler.CompileAssemblyFromSource(cmpParams, codeString);

            //			foreach (System.CodeDom.Compiler.CompilerError ce in results.Errors)
            //				this.Put(ce.ErrorText);

            if (results.Errors.Count == 0 && results.CompiledAssembly!=null)
            {
                System.Reflection.MethodInfo methodInfo = results.CompiledAssembly.EntryPoint;
                return methodInfo.Invoke(null, null);
            }
            return null;
        }
Beispiel #16
0
        protected static string CompileAssembly(string outputPath, IEnumerable <string> sources, IEnumerable <string> assemblyReferences)
        {
            var directory = Path.GetDirectoryName(outputPath);

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

            var codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();
            var p = new CompilerParameters();

            p.OutputAssembly          = outputPath;
            p.IncludeDebugInformation = true;
            p.CompilerOptions         = "/o- /debug+ /d:UNITY_EDITOR /noconfig /warn:0";

            if (assemblyReferences != null)
            {
                p.ReferencedAssemblies.AddRange(
                    assemblyReferences.Where(an => !an.Contains("mscorlib.dll") && !an.Contains("System.dll")).ToArray());
            }

            p.ReferencedAssemblies.Add(typeof(Enumerable).Assembly.Location);

            var compilerResult = codeDomProvider.CompileAssemblyFromSource(p, sources.ToArray());

            if (compilerResult.Errors.Count > 0)
            {
                throw new Exception(compilerResult.Errors.OfType <CompilerError>().Aggregate("", (acc, curr) => acc + "\r\n" + curr.ErrorText));
            }

            return(compilerResult.PathToAssembly);
        }
Beispiel #17
0
        /// <summary>
        /// 动态编译
        /// </summary>
        /// <param name="formula">需编译的内容</param>
        /// <param name="returnType">返回类型</param>
        /// <param name="obj">参数</param>
        /// <returns></returns>
        public static object Calculate(string formula, string returnType, object obj)
        {
            try
            {
                string paramExp = obj.GetType().ToString() + " obj";
                object calculated = null;

                Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters parameter = new System.CodeDom.Compiler.CompilerParameters();
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.GenerateExecutable = false; //<--不要生成 EXE 文件
                parameter.GenerateInMemory = true; //在内存中运行
                string codeDom = GenerateCodeBlocks(formula, returnType, paramExp);
                System.CodeDom.Compiler.CompilerResults result = provider.CompileAssemblyFromSource(parameter,codeDom);//动态编译后的结果

                if (result.Errors.Count > 0)
                {
                    return null;
                }
                System.Reflection.MethodInfo newMethod = result.CompiledAssembly.GetType("Maike.Calculation").GetMethod("dowork");
                calculated = result.CompiledAssembly.GetType("Maike.Calculation").GetMethod("dowork").Invoke(null, new object[] { obj });

                return calculated;
            }
            catch
            {
                return null;
            }
        }
      public static string RunScript(string scriptCode, string scriptParameter)
      {
 
          CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
          //configure parameters
          CompilerParameters parameters = new CompilerParameters();
          parameters.GenerateExecutable = false;
          parameters.GenerateInMemory = true;
          parameters.IncludeDebugInformation = false;
          string reference;
          // Set reference to current assembly - this reference is a hack for the example..
          reference = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
          parameters.ReferencedAssemblies.Add(reference+"\\CompileScriptExample.exe");
          //compile
          CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { scriptCode });
          if (results.Errors.Count == 0)
          {
              IStringManipulator compiledScript=(IStringManipulator)FindInterface(results.CompiledAssembly, "IStringManipulator");
              return compiledScript.processString(scriptParameter);//run the script, pass the string param..
          }
          else
          {
              foreach(CompilerError anError in results.Errors)
              {
                  MessageBox.Show(anError.ErrorText);
              }
              //handle compilation errors here
              //..use results.errors collection
              throw new Exception("Compilation error...");
          }
      }
Beispiel #19
0
        private static Type GenerateAccountType(AccountType accountType)
        {
            var provider   = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters {
                GenerateInMemory = true, GenerateExecutable = false
            };

            parameters.ReferencedAssemblies.Add("system.dll");
            parameters.ReferencedAssemblies.Add(typeof(System.Linq.IQueryable).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(Entity).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(AccountType).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(Account).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(System.ServiceModel.OperationContext).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(TransactRules.Calculations.AccrualCalculation).Assembly.Location);

            var accountTemplate = new AccountClassTemplate {
                Model = accountType
            };

            var code = accountTemplate.TransformText();

            var compilerResults = provider.CompileAssemblyFromSource(parameters, code);

            if (compilerResults.Errors.Count > 0)
            {
                ThrowCompilerException(accountType, compilerResults);
            }

            var generatedType = compilerResults.CompiledAssembly.GetType(GetTypeName(accountType));

            return(generatedType);
        }
Beispiel #20
0
        /// <summary>
        /// Compile a script, using the source and reference assemblies specified.  The return value will have the executable object
        /// and any errors encountered.
        /// </summary>
        /// <param name="Source">The source to compile as a string.</param>
        /// <param name="Reference">array of strings, each representing an assebmly or namespace to include.</param>
        /// <param name="Language">The Languages enumeration value for the code language.</param>
        /// <param name="DebugInformation">Whether to include debug information in the compiled object.</param>
        /// <returns></returns>
        public static CompilerResults CompileScript(string Source, string[] Reference, Languages Language, bool DebugInformation)
        {
            CodeDomProvider provider = null;
            CompilerResults results;

            switch (Language)
            {
            case Languages.VBnet:
                provider = new Microsoft.VisualBasic.VBCodeProvider();
                break;

            case Languages.CSharp:
                provider = new Microsoft.CSharp.CSharpCodeProvider();
                break;
            }

            // Configure parameters
            CompilerParameters parms = new CompilerParameters();

            parms.GenerateExecutable      = false;
            parms.GenerateInMemory        = true;
            parms.IncludeDebugInformation = DebugInformation;
            if (Reference != null)
            {
                foreach (string r in Reference)
                {
                    parms.ReferencedAssemblies.Add(r);
                }
            }

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

            return(results);
        }
Beispiel #21
0
        public static string ParseString(string input)
        {
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
            };

            var code = @"
            namespace Tmp
            {
                public class TmpClass
                {
                    public static string GetValue()
                    {
                        return """ + input + @""";
                    }
                }
            }";

            var compileResult = provider.CompileAssemblyFromSource(parameters, code);

            if (compileResult.Errors.HasErrors)
            {
                return input;
                //throw new ArgumentException(compileResult.Errors.Cast<System.CodeDom.Compiler.CompilerError>().First(e => !e.IsWarning).ErrorText);
            }

            var asmb = compileResult.CompiledAssembly;
            var method = asmb.GetType("Tmp.TmpClass").GetMethod("GetValue");

            return method.Invoke(null, null) as string;
        }
Beispiel #22
0
        public static void createAssembly(string code)
        {
            string[] sources = { code };
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;
            parameters.GenerateExecutable = (bool)launchArguments.flags["createbinary"];
            if ((bool)launchArguments.flags["createbinary"])
                parameters.OutputAssembly = IO.getExePath();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.Drawing.dll");

            using (Microsoft.CSharp.CSharpCodeProvider CodeProv =
            new Microsoft.CSharp.CSharpCodeProvider())
            {
                CompilerResults results = CodeProv.CompileAssemblyFromSource(parameters, sources);

                if (results.Errors.HasErrors)
                    debug.throwException("Compilation error", String.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select(n => n.ToString())), debug.importance.Fatal);

                if (!(bool)launchArguments.flags["createbinary"])
                {
                    Console.WriteLine("Initializing ListSharp");

                    var type = results.CompiledAssembly.GetType("MainClass");
                    var obj = Activator.CreateInstance(type);
                    var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
                    Console.WriteLine(output);
                }
            }
        }
Beispiel #23
0
        private Type[] CompileClasses(string assemblyName, List <string> listSources)
        {
            Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            CompilerParameters cpTemp = new CompilerParameters();

            cpTemp.OutputAssembly     = assemblyName;
            cpTemp.GenerateExecutable = false;
            cpTemp.GenerateInMemory   = true;


            Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(p => !p.IsDynamic).ToArray();

            foreach (Assembly assembly in loadedAssemblies)
            {
                cpTemp.ReferencedAssemblies.Add(assembly.Location);
            }

            CompilerResults crTemp = provider.CompileAssemblyFromSource(cpTemp, listSources.ToArray());

            if (crTemp.Errors.HasErrors)
            {
                throw new MCoreExceptionPopup("Unable to compile Plugin Sims. First error:\n{0}", crTemp.Errors[0].ErrorText);
            }
            return(crTemp.CompiledAssembly.GetTypes());
        }
Beispiel #24
0
        static Assembly CompileCode(string code)
        {
            Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters options = new CompilerParameters();

            options.GenerateExecutable = false;
            options.GenerateInMemory   = true;

            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            //Add references to ScriptingInterface.dll
            String pathToScriptingInterfaceDll = Path.Combine(Environment.CurrentDirectory, "ScriptingInterface.dll");

            options.ReferencedAssemblies.Add(pathToScriptingInterfaceDll);
            // Compile our code
            CompilerResults result;

            result = csProvider.CompileAssemblyFromSource(options, code);
            if (result.Errors.HasErrors)
            {
                // Report back to the user that the script has errored
                Console.WriteLine("Script has errored");
                for (int i = 0; i < result.Errors.Count; i++)
                {
                    Console.WriteLine("Error {0}: {1}", i + 1, result.Errors[i]);
                }
                return(null);
            }
            if (result.Errors.HasWarnings)
            {
                Console.WriteLine("Script has warnings");
            }
            return(result.CompiledAssembly);
        }
Beispiel #25
0
        public CompilerResults Compile()
        {
            // init
            var guid     = Guid.NewGuid().ToString();
            var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), guid);

            // create temp path
            System.IO.Directory.CreateDirectory(tempPath);

            // options
            var options = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                OutputAssembly          = System.IO.Path.Combine(tempPath, string.Format("{0}.dll", guid)),
                TempFiles = new TempFileCollection(tempPath, false)
            };

            // references
            var references = new Type[] { typeof(string), typeof(Enumerable), typeof(Processor) };

            options.ReferencedAssemblies.AddRange(references
                                                  .Select(x => x.Assembly)
                                                  .Where(x => !x.IsDynamic)
                                                  .GroupBy(x => x.FullName)
                                                  .Select(x => x.First().Location)
                                                  .ToArray());

            // compile
            return(_CodeProvider.CompileAssemblyFromSource(options, this.ToString()));
        }
        static void Main()
        {
            var s = @"using System.CodeDom.Compiler;using System.Diagnostics;class P{static void Main(){var s = {0}{1}{0};var t = ;using (var p = new Microsoft.CSharp.CSharpCodeProvider()){var o = new CompilerParameters(new string[] { ""System.dll"" }) { GenerateExecutable = true };t = p.CompileAssemblyFromSource(o, s).PathToAssembly;}var i = new ProcessStartInfo(t) { UseShellExecute = false, CreateNoWindow = true };System.IO.File.Delete(t);}}";

            s = string.Format(s, s, '"');

            var t = "";

            using (var p = new Microsoft.CSharp.CSharpCodeProvider())
            {
                var o = new CompilerParameters(new string[] { "System.dll" })
                {
                    GenerateExecutable = true
                };
                var r = p.CompileAssemblyFromSource(o, s);
                t = r.PathToAssembly;
            }

            var i = new ProcessStartInfo(t)
            {
                UseShellExecute = false, CreateNoWindow = true
            };

            Process.Start(i).WaitForExit();
            System.IO.File.Delete(t);
        }
Beispiel #27
0
        public Type GenerateClass(string tableName, List <string> columns)
        {
            StringBuilder classBuilder = new StringBuilder();

            classBuilder.Append(String.Format(" public class {0} ", tableName));
            classBuilder.Append(String.Format(" {0} ", "{"));
            foreach (var item in columns)
            {
                classBuilder.Append(String.Format(@" public string {0} {{ get; set; }} ", item));
            }
            classBuilder.Append(String.Format(" {0} ", "}"));
            string stringClassCode = classBuilder.ToString();

            using (Microsoft.CSharp.CSharpCodeProvider foo =
                       new Microsoft.CSharp.CSharpCodeProvider())
            {
                var res = foo.CompileAssemblyFromSource(
                    new System.CodeDom.Compiler.CompilerParameters()
                {
                    GenerateInMemory = true
                },
                    stringClassCode
                    );
                return(res.CompiledAssembly.GetType(tableName));
            }
        }
Beispiel #28
0
        private void CompileApp(int rc, string pathToExe)
        {
            Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();

            //System.CodeDom.Compiler.ICodeCompiler csharpCompiler = csharp.CreateCompiler();

            var cp = new System.CodeDom.Compiler.CompilerParameters();

            cp.GenerateInMemory        = false;
            cp.GenerateExecutable      = true;
            cp.IncludeDebugInformation = false;
            cp.OutputAssembly          = pathToExe;

            // set the return code in the app
            var cr = csharp.CompileAssemblyFromSource(cp, programCode.Replace("@@XXX@@", rc.ToString()));

            if (cr == null)
            {
                throw new Exception("Errors compiling!");
            }

            foreach (string s in cr.Output)
            {
                TestContext.WriteLine(s);
            }

            if (cr.Errors.Count != 0)
            {
                throw new Exception("Errors compiling!");
            }
        }
Beispiel #29
0
        public CSharpScript(String code)
        {
            using (var provider =
                       new Microsoft.CSharp.CSharpCodeProvider())
            {
                var builder = new StringBuilder();
                builder
                .AppendLine("using System;")
                .AppendLine("using System.Collections.Generic;")
                .AppendLine("using System.Linq;")
                .AppendLine("using System.Reflection;")
                .AppendLine("using System.Text;")
                .AppendLine("using LiveSplit;")
                .AppendLine("using LiveSplit.Model;")
                .AppendLine("using LiveSplit.Web;")
                .AppendLine("using LiveSplit.Web.Share;")
                .AppendLine("public class CompiledScript")
                .AppendLine("{")
                .AppendLine("public void Respond(string message)")
                .AppendLine("{")
                .AppendLine("Twitch.Instance.Chat.SendMessage(message);")
                .AppendLine("}")
                .AppendLine("public void Execute(LiveSplitState state, TwitchChat.User user, string arguments)")
                .AppendLine("{")
                .Append(code)
                .AppendLine("}")
                .AppendLine("}");

                var parameters = new System.CodeDom.Compiler.CompilerParameters()
                {
                    GenerateInMemory = true,
                    CompilerOptions  = "/optimize",
                };
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("LiveSplit.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Data.dll");
                parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
                parameters.ReferencedAssemblies.Add("System.Drawing.dll");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
                parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");

                var res = provider.CompileAssemblyFromSource(parameters, builder.ToString());

                if (res.Errors.HasErrors)
                {
                    var errorMessage = "";
                    foreach (var error in res.Errors)
                    {
                        errorMessage += error + "\r\n";
                    }
                    throw new ArgumentException(errorMessage, "code");
                }

                var type = res.CompiledAssembly.GetType("CompiledScript");
                CompiledCode = Activator.CreateInstance(type);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Compiles the user code into an assembly.
        /// </summary>
        /// <param name="errors">Compiler errors if any</param>
        public Assembly Compile(out CompilerErrorCollection errors)
        {
            // Create a code provider
            // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones)
            // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that
            // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?)
            Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();

            // Setup our options
            CompilerParameters options = new CompilerParameters();

            options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net)
            options.GenerateInMemory   = true;  // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile
            // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best!

            // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow
            // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows
            // thus they can only do the things you want them to.
            // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it)
            // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another
            // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to
            // the "script"
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            options.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            options.ReferencedAssemblies.Add("System.dll");

            // Compile our code
            CompilerResults result;

            result = csProvider.CompileAssemblyFromSource(options, codeTemplate.Replace("{0}", this.Code));

            errors = result.Errors;
            return(errors.HasErrors ? null : result.CompiledAssembly);
        }
        public static Assembly CompileSource(string source, List <string> references)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Scripts\");

            IOUtil.SafeCreateDirectory(path);
            File.WriteAllText(@"{1}{0}.cs".FormatWith(DateTime.Now.ToString("yyMMddhhmmss"), path), source);

            //string oldDirectory = Directory.GetCurrentDirectory();
            //FileInfo fileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);
            //Directory.SetCurrentDirectory(fileInfo.Directory.FullName);
            Assembly        generatedAssembly = null;
            CodeDomProvider codeProvider      = new Microsoft.CSharp.CSharpCodeProvider();

            CompilerParameters compilerParameters = new CompilerParameters();

            compilerParameters.CompilerOptions    = "/target:library /optimize";
            compilerParameters.GenerateExecutable = false;
            compilerParameters.GenerateInMemory   = true;
            compilerParameters.ReferencedAssemblies.Add("System.Data.dll");
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Xml.dll");
            compilerParameters.ReferencedAssemblies.Add("Bee.Core.dll");

            if (references != null && references.Count > 0)
            {
                compilerParameters.ReferencedAssemblies.AddRange(references.ToArray());
            }

            CompilerResults compilerResults;

            try
            {
                compilerResults =
                    codeProvider.CompileAssemblyFromSource(compilerParameters, source);
            }
            catch (NotImplementedException ex)
            {
                throw new CoreException("Occurs errors when compiling.", ex);
            }

            //Directory.SetCurrentDirectory(oldDirectory);

            if (compilerResults.Errors.Count > 0)
            {
                StringBuilder stringBuilder = new StringBuilder();

                foreach (CompilerError compilerError in compilerResults.Errors)
                {
                    stringBuilder.Append(string.Format("第{0}行 第{1}列 出错了:{2}",
                                                       compilerError.Line, compilerError.Column, compilerError.ErrorText));
                }

                throw new CoreException("compile-errors", new ApplicationException(stringBuilder.ToString()));
            }
            else
            {
                generatedAssembly = compilerResults.CompiledAssembly;
            }
            return(generatedAssembly);
        }
Beispiel #32
0
        /// <summary>
        /// Compile native source code for a set of proxy classes corresponding to
        /// the object and classSerializerHelperName classes described in the federation
        /// description document.  Any existing files will be overwritten.
        /// </summary>
        public virtual void CompileProxies()
        {
            //make sure the Target directory is present.  Defensive programming
            //ot make sure we dont' go forward while our directories aren't setup.
            Directory.CreateDirectory(this.TargetDirectory.FullName);

            string result = GenerateProxiesCodeToMemoryStream();

            //code generator and code provider
            Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            string[] assemblyNames = new string[] { "Sxta1516.dll", "Rti1516.dll" };
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(assemblyNames);
            parameters.GenerateInMemory   = true;
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly     = "Proxys.dll";
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, result);

            if (results.Errors.Count > 0)
            {
                foreach (CompilerError CompErr in results.Errors)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("Line Number " + CompErr.Line + ", Error Code: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";");
                    }
                }
            }
        }
Beispiel #33
0
            public object MathCalculator(string expression)
            {
                object retvar = null;

                Microsoft.CSharp.CSharpCodeProvider        provider = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters cp       = new System.CodeDom.Compiler.CompilerParameters(
                    new string[] { @"System.dll" });
                StringBuilder builder = new StringBuilder("using System;class CalcExp{public static object Calc(){ return \"expression\";}}");

                builder.Replace("\"expression\"", expression);
                string code = builder.ToString();

                System.CodeDom.Compiler.CompilerResults results;
                results = provider.CompileAssemblyFromSource(cp, new string[] { code });
                if (results.Errors.HasErrors)
                {
                    retvar = null;
                }
                else
                {
                    System.Reflection.Assembly a = results.CompiledAssembly;
                    Type t = a.GetType("CalcExp");
                    retvar = t.InvokeMember("Calc", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod
                                            , System.Type.DefaultBinder, null, null);
                }
                return(retvar);
            }
        protected NPath Compile(string testAssemblyName, string sourceCode, params string[] dependentAssemblyNames)
        {
            // prefix the assembly name because they are globally unique and don't want to ever collide
            var testAssemblyPath = BaseDir
                                   .Combine($"{TestContext.CurrentContext.GetFixtureName()}_{testAssemblyName}")
                                   .ChangeExtension(".dll");

            // set up to compile

            var compiler     = new Microsoft.CSharp.CSharpCodeProvider();
            var compilerArgs = new CompilerParameters
            {
                OutputAssembly          = testAssemblyPath,
                IncludeDebugInformation = true,
                CompilerOptions         = "/o- /debug+ /warn:0"
            };

            compilerArgs.ReferencedAssemblies.Add(typeof(int).Assembly.Location); // mscorlib

            // TODO: use typecache
            var assemblies = AppDomain.CurrentDomain
                             .GetAssemblies()
                             .Where(a => !a.IsDynamic)
                             .ToDictionary(a => a.GetName().Name, a => a.Location.ToNPath(), StringComparer.OrdinalIgnoreCase);

            foreach (var dependentAssemblyName in dependentAssemblyNames)
            {
                // we may have already copied it in
                var path = BaseDir.Combine(dependentAssemblyName).ChangeExtension(".dll");

                // if not,
                if (!path.Exists() && assemblies.TryGetValue(dependentAssemblyName, out path))
                {
                    path.Copy(BaseDir.Combine(path.FileName));
                }

                compilerArgs.ReferencedAssemblies.Add(path);
            }

            // compile and handle errors

            var compilerResult = compiler.CompileAssemblyFromSource(compilerArgs, sourceCode);

            if (compilerResult.Errors.Count > 0)
            {
                var errorText = compilerResult.Errors
                                .OfType <CompilerError>()
                                .Select(e => $"({e.Line},{e.Column}): error {e.ErrorNumber}: {e.ErrorText}")
                                .Prepend("Compiler errors:")
                                .StringJoin("\n");
                throw new Exception(errorText);
            }

            testAssemblyPath.ShouldBe(new NPath(compilerResult.PathToAssembly));

            PeVerify.Verify(testAssemblyPath); // sanity check on what the compiler generated

            return(testAssemblyPath);
        }
Beispiel #35
0
        public CompilerResults CompileCode(string code)
        {
#if NET_2_0
            return(provider.CompileAssemblyFromSource(options, code));
#else
            return(compiler.CompileAssemblyFromSource(options, code));
#endif
        }
Beispiel #36
0
        public static Assembly CompileExecutable(CompilerParameters cp, String[] code)
        {
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            CompilerResults cr = provider.CompileAssemblyFromSource(cp, code);

            return(processCompilationResult(cr));
        }
Beispiel #37
0
        static void Main(string[] args)
        {
            CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();

            string[] assemblyNames = new string[]{
                "mscorlib.dll",
                "System.dll",
                "System.Data.dll",
                "System.Drawing.dll",
                "System.Xml.dll",
                "System.Core.dll",
                "System.Windows.Forms.dll"
            };

            CompilerParameters compilerParameters = new CompilerParameters(assemblyNames){
                OutputAssembly = "OutputAssembly.dll",
                GenerateExecutable = false,
                GenerateInMemory = true,
                WarningLevel = 3,
                CompilerOptions = "/optimize",
                IncludeDebugInformation = false,
                //TempFiles = new TempFileCollection(".", true)
            };

            CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(
                compilerParameters,
                new string[] { Code });

            /* This prints low-level messages like this, as well as error messages:
                *
                * G:\tmp\CsCompilerTest\WorkingDir> "C:\Windows\Microsoft.NET\Framework\v4.0.30319
                * \csc.exe" /t:library /utf8output /out:"C:\Users\Adam Sawicki\AppData\Local\Temp\
                * 0pdzupen.dll" /debug- /optimize+ /w:3 /optimize  "C:\Users\Adam Sawicki\AppData\
                * Local\Temp\0pdzupen.0.cs"

                * Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
                * Copyright (C) Microsoft Corporation. All rights reserved.
                */
            foreach (String message in compilerResults.Output)
                Console.WriteLine(message);

            /* This prints error messages in form of:
                *
                * c:\Users\Adam Sawicki\AppData\Local\Temp\4kbqoyz2.0.cs(7,9) : error CS0103: The
                * name 'Console' does not exist in the current context
                */
            //foreach (CompilerError error in compilerResults.Errors)
            //    Console.WriteLine(error.ToString());

            Assembly assembly = compilerResults.CompiledAssembly;
            if (assembly == null) return;

            object obj = assembly.CreateInstance("MainClass");
            if (obj == null) return;

            Type type = obj.GetType();
            type.InvokeMember("Main", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, obj, new object[] { });
        }
Beispiel #38
0
        public Assembly CreateAssemblyFromSourceCode(string extension, IList references, params string[] sourcecode)
        {
            compilerErrors = null;


            CodeDomProvider codeProvider = null;

            switch (extension.ToLower())
            {
            case ".cs":
                codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                break;

            case ".vb":
                codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                break;

            default:
                throw new InvalidOperationException("Script files must have a .cs or .vb.");
            }

            CompilerParameters compilerParams = new CompilerParameters();

            compilerParams.CompilerOptions         = "/target:library /optimize";
            compilerParams.GenerateExecutable      = false;
            compilerParams.GenerateInMemory        = true;
            compilerParams.IncludeDebugInformation = false;

            compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");


            foreach (string reference in references)
            {
                if (!compilerParams.ReferencedAssemblies.Contains(reference))
                {
                    compilerParams.ReferencedAssemblies.Add(reference);
                }
            }
            CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams, sourcecode);


            if (results.Errors.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError item in results.Errors)
                {
                    sb.AppendFormat("{0} line:{1}   {2}\r\n", item.FileName, item.Line, item.ErrorText);
                }
                compilerErrors = results.Errors;
                throw new Exception(
                          "Compiler error(s)\r\n" + sb.ToString());
            }

            Assembly createdAssembly = results.CompiledAssembly;

            return(createdAssembly);
        }
Beispiel #39
0
        public Assembly CreateAssemblyFromSourceCode(string extension, IList references, params string[] sourcecode)
        {
            compilerErrors = null;


            CodeDomProvider codeProvider = null;
            switch (extension.ToLower())
            {
                case ".cs":
                    codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
                case ".vb":
                    codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
                default:
                    throw new InvalidOperationException("Script files must have a .cs or .vb.");
            }

            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.CompilerOptions = "/target:library /optimize";
            compilerParams.GenerateExecutable = false;
            compilerParams.GenerateInMemory = true;
            compilerParams.IncludeDebugInformation = false;

            compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");


            foreach (string reference in references)
            {
                if (!compilerParams.ReferencedAssemblies.Contains(reference))
                {
                    compilerParams.ReferencedAssemblies.Add(reference);
                }
            }
            CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams, sourcecode);


            if (results.Errors.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError item in results.Errors)
                {
                    sb.AppendFormat("{0} line:{1}   {2}\r\n", item.FileName, item.Line, item.ErrorText);
                }
                compilerErrors = results.Errors;
                throw new Exception(
                    "Compiler error(s)\r\n" + sb.ToString());
            }

            Assembly createdAssembly = results.CompiledAssembly;

            return createdAssembly;
        }
        public ASLMethod(String code)
        {
            using (var provider =
                new Microsoft.CSharp.CSharpCodeProvider())
            {
                var builder = new StringBuilder();
                builder
                    .AppendLine("using System;")
                    .AppendLine("using System.Collections.Generic;")
                    .AppendLine("using System.Linq;")
                    .AppendLine("using System.Reflection;")
                    .AppendLine("using System.Text;")
                    .AppendLine("public class CompiledScript")
                    .AppendLine("{")
                        .AppendLine("public dynamic Execute(dynamic timer, dynamic old, dynamic current)")
                        .AppendLine("{")
                            .Append(code)
                            .Append("return null;")
                        .AppendLine("}")
                    .AppendLine("}");

                var parameters = new System.CodeDom.Compiler.CompilerParameters()
                    {
                        GenerateInMemory = true,
                        CompilerOptions = "/optimize",
                    };
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Data.dll");
                parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
                parameters.ReferencedAssemblies.Add("System.Drawing.dll");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
                parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");

                var res = provider.CompileAssemblyFromSource(parameters, builder.ToString());

                if (res.Errors.HasErrors)
                {
                    var errorMessage = "";
                    foreach (var error in res.Errors)
                    {
                        errorMessage += error + "\r\n";
                    }
                    throw new ArgumentException(errorMessage, "code");
                }

                var type = res.CompiledAssembly.GetType("CompiledScript");
                CompiledCode = Activator.CreateInstance(type);
            }
        }
        // Compile all the scripts into one assembly.
        public ScriptCompileResult Compile(string code)
        {
            ScriptCompileResult result	= new ScriptCompileResult();
            string pathToAssembly = "";
            bool hasErrors = false;

            // Setup the compile options.
            CompilerParameters options	= new CompilerParameters();
            options.GenerateExecutable	= false;	// We want a Dll (Class Library)
            options.GenerateInMemory	= false;	// Save the assembly to a file.
            options.OutputAssembly		= "ZWD2CompiledScript.dll";

            // Add the assembly references.
            options.ReferencedAssemblies.Add(GetZeldaAPIAssembly().Location);

            // Create a C# code provider and compile the code.
            // The 'using' statement is necessary so the created DLL file isn't
            // locked when we try to load its contents.
            using (Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider()) {
                CompilerResults csResult = csProvider.CompileAssemblyFromSource(options, code);
                pathToAssembly	= csResult.PathToAssembly;
                hasErrors		= csResult.Errors.HasErrors;

                // Copy warnings and errors into the ScriptComileResult result.
                foreach (CompilerError csError in csResult.Errors) {
                    ScriptCompileError error = new ScriptCompileError(csError.Line,
                        csError.Column, csError.ErrorNumber, csError.ErrorText, csError.IsWarning);
                    if (error.IsWarning)
                        result.Warnings.Add(error);
                    else
                        result.Errors.Add(error);
                }
            }

            // If the compile was successful, then load the created.
            // DLL file into memory and then delete the file.
            if (!hasErrors) {
                result.RawAssembly = File.ReadAllBytes(pathToAssembly);
                //rawAssembly = result.RawAssembly;
                File.Delete(pathToAssembly);
            }
            else {
                //rawAssembly = null;
            }

            return result;
        }
        static void Main()
        {
            var s = @"using System.CodeDom.Compiler;using System.Diagnostics;class P{static void Main(){var s = {0}{1}{0};var t = ;using (var p = new Microsoft.CSharp.CSharpCodeProvider()){var o = new CompilerParameters(new string[] { ""System.dll"" }) { GenerateExecutable = true };t = p.CompileAssemblyFromSource(o, s).PathToAssembly;}var i = new ProcessStartInfo(t) { UseShellExecute = false, CreateNoWindow = true };System.IO.File.Delete(t);}}";
            s = string.Format(s, s, '"');

            var t = "";
            using (var p = new Microsoft.CSharp.CSharpCodeProvider())
            {
                var o = new CompilerParameters(new string[] { "System.dll" }) { GenerateExecutable = true };
                var r = p.CompileAssemblyFromSource(o, s);
                t = r.PathToAssembly;
            }

            var i = new ProcessStartInfo(t) { UseShellExecute = false, CreateNoWindow = true };
            Process.Start(i).WaitForExit();
            System.IO.File.Delete(t);
        }
Beispiel #43
0
        public static void Main(string[] args)
        {
            List<string> sources = new List<string>();
            string cscode = "using System.Windows.Forms;\n";
            foreach (string filename in args)
            {
                if (filename.EndsWith(".wtf"))
                {
                    WindowsTextFoundation.Core.WindowsTextFoundation wtf = WindowsTextFoundation.Core.WindowsTextFoundation.FromFile(filename);
                    cscode += @"namespace WTFCSharp
{
public class WTFCSharp
{
public WTFCSharp()" + "\r\n{\r\n" +
                        wtf.Objects[0].ToCSharp() +
@"frm.ShowDialog();" +  //FIXME: INJECT INTO C# CODE
@"}
}
}";
                }
                else 
                {
                    sources.Add(System.IO.File.ReadAllText(filename));
                }
            }
            sources.Add(cscode);
            Console.WriteLine(cscode);
            Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Drawing.dll");
            cp.GenerateExecutable = true;
            cp.OutputAssembly = "wtfcs.exe";
            cp.MainClass = "WTFCSharpTest.a"; //FIXME
            CompilerResults r = csc.CompileAssemblyFromSource(cp,sources.ToArray());
            if (r.Errors.Count != 0)
            {
                foreach (CompilerError err in r.Errors)
                {
                    Console.WriteLine(err.ToString());
                }
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Beispiel #44
0
        private static string CreateAssembly(string assemblyPath)
        {
            ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();

            string source = LoadSource(Path.GetFileNameWithoutExtension(assemblyPath));

            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false;
            options.GenerateInMemory = false;
            options.OutputAssembly = assemblyPath;
            options.ReferencedAssemblies.Add(Path.Combine(Path.GetDirectoryName(assemblyPath) ,"MbUnit.Framework.dll"));

            CompilerResults results = compiler.CompileAssemblyFromSource(options, source);
            if (results.Errors.HasErrors)
                CompilerAssert.DisplayErrors(results, Console.Out);
            Assert.IsFalse(results.Errors.HasErrors);
            return results.PathToAssembly;
        }
        public static Assembly CreateAssembly(string name)
        {
            ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();

            string source = LoadSource(name);

            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false;
            options.GenerateInMemory = false;
            options.OutputAssembly = name+".dll";
            options.ReferencedAssemblies.Add("MbUnit.Framework.dll");

            CompilerResults results = compiler.CompileAssemblyFromSource(options, source);
            if (results.Errors.HasErrors)
                CompilerAssert.DisplayErrors(results, Console.Out);
            Assert.IsFalse(results.Errors.HasErrors);
            return results.CompiledAssembly;
        }
Beispiel #46
0
        public static string RunScript(string scriptCode, string scriptParameter)
        {
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            //configure parameters
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = false;
            parameters.IncludeDebugInformation = false;
            string reference;
            // Set reference to current assembly - this reference is a hack for the example..
            reference = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            parameters.ReferencedAssemblies.Add(reference + "\\xUnitTestSuiteGenerator.exe");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("mscorlib.dll");

            //compile
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { scriptCode });

            if (results.Errors.Count == 0)
            {

                IStringManipulator compiledScript=(IStringManipulator)FindInterface(results.CompiledAssembly, "IStringManipulator");
                try
                {
                   return compiledScript.processString(scriptParameter);//run the script, pass the string param..
                }catch(OverflowException e){
                   throw e;

                }

            }
            else
            {
                foreach(CompilerError anError in results.Errors)
                {
                    MessageBox.Show(anError.ErrorText);
                }
                //handle compilation errors here
                //..use results.errors collection
                throw new Exception("Compilation error...");
            }
        }
Beispiel #47
0
        private void View_CompileButtonClicked(object sender, EventArgs e)
        {
            using(CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                CompilerParameters parameters = new CompilerParameters();
                parameters.GenerateExecutable = false;
                parameters.GenerateInMemory = true;
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);

                CompilerResults results = provider.CompileAssemblyFromSource(parameters, this.view.SourceCode);

                if (results.Errors.Count == 0)
                {
                    this.view.ClearCompilerErrors();

                    this.program = null;

                    foreach (Type type in results.CompiledAssembly.GetTypes())
                    {
                        if (type.GetInterface(typeof(ITurtleGraphicsProgram).ToString(), true) != null)
                            this.program = (ITurtleGraphicsProgram)results.CompiledAssembly.CreateInstance(type.FullName);
                    }

                    if (this.program != null)
                    {
                        this.view.RedrawScene();
                    }
                    else
                    {
                        // TODO: Show error message here if no type implements ITurtleGraphicsProgram.
                    }
                }
                else
                {
                    List<CompilerError> errors = new List<CompilerError>();
                    foreach (CompilerError error in results.Errors)
                        errors.Add(error);

                    this.view.SetCompilerErrors(errors);
                }
            }
        }
        public static void Main(string[] args)
        {
            var result = CommandLine.Parser.Default.ParseArguments<CommandLineOptions>(args);

            if (!result.Errors.Any()) {
                Console.WriteLine("Compilling Grammar...");

                string code = string.Empty;

                try {
                    code = GetCode(result.Value);
                } catch (Exception e) {
                    Console.WriteLine(e.Message);
                }

                if (result.Value.GenerateSource) {
                    File.WriteAllText(result.Value.GrammarName + ".cs", code);
                }

                if (!result.Value.SourceOnly) {
                    var compiler = new Microsoft.CSharp.CSharpCodeProvider();
                    var cp = new CompilerParameters();

                    cp.GenerateExecutable = false;
                    cp.ReferencedAssemblies.Add(typeof(EbnfGrammar).Assembly.Location);
                    cp.GenerateInMemory = false;
                    cp.OutputAssembly = result.Value.GrammarName + ".dll";

                    var cRes = compiler.CompileAssemblyFromSource(cp, new [] { code });

                    if (cRes.Errors.HasErrors) {
                        foreach (CompilerError e in cRes.Errors) {
                            Console.WriteLine(e.Line + ": " + e.ErrorText);
                        }
                    }
                }

                Console.WriteLine("Done");
            }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Beispiel #49
0
        private void LibraryStub()
        {
            var path = Path.Combine(Path.GetTempPath(), "DynamicEmployee.dll");

            const string source = @"
namespace DynamicEmployee
{
    public class Employee { }
}";
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            provider.CompileAssemblyFromSource(new CompilerParameters { OutputAssembly = path }, source);

            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[(int)fs.Length];
                fs.Read(buffer, 0, buffer.Length);

                AppDomain.CurrentDomain.Load(buffer);
            }
        }
Beispiel #50
0
 static Assembly CompileCode(string code)
 {
     Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
     CompilerParameters options = new CompilerParameters();
     options.GenerateExecutable = false;
     options.GenerateInMemory = true;
     string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
     string[] dlls1 = Directory.GetFiles(path, "Amarok86*.dll");
     string[] dlls2 = Directory.GetFiles(path, "Gibbed.*.dll");
     string[] dlls3 = Directory.GetFiles(path, "SaltTPF.dll");
     options.ReferencedAssemblies.AddRange(dlls1.Select(f => Path.Combine(path, f)).ToArray());
     options.ReferencedAssemblies.AddRange(dlls2.Select(f => Path.Combine(path, f)).ToArray());
     options.ReferencedAssemblies.AddRange(dlls2.Select(f => Path.Combine(path, f)).ToArray());
     options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
     options.ReferencedAssemblies.Add(Path.Combine(path, "ME3Explorer.exe"));
     options.ReferencedAssemblies.Add("System.dll");
     options.ReferencedAssemblies.Add("System.Core.dll");
     options.ReferencedAssemblies.Add("System.Windows.Forms.dll");
     options.ReferencedAssemblies.Add("System.Data.Linq.dll");
     CompilerResults result = null;
     try
     {
         result = csProvider.CompileAssemblyFromSource(options, code);
     }
     catch (Exception exc)
     {
         MessageBox.Show("Exception caught: " + exc.Message);
     }
     if (result.Errors.HasErrors)
     {
         string error = "";
         error += "Line: " + result.Errors[0].Line + "  Column: " + result.Errors[0].Column + "\n";
         error += "(" + result.Errors[0].ErrorNumber + ")\n" + result.Errors[0].ErrorText;
         MessageBox.Show(error, "Script Compiler", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return null;
     }
     if (result.Errors.HasWarnings)
     {
     }
     return result.CompiledAssembly;
 }
Beispiel #51
0
        static Assembly CompileCode(string code)
        {
            // Create a code provider
            // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones)
            // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that
            // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?)
            Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();

            // Setup our options
            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net)
            options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile
            // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best!

            // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow
            // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows
            // thus they can only do the things you want them to.
            // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it)
            // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another
            // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to
            // the "script"
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

            // Compile our code
            CompilerResults result;
            result = csProvider.CompileAssemblyFromSource(options, code);

            if (result.Errors.HasErrors)
            {
                // TODO: report back to the user that the script has errored
                return null;
            }

            if (result.Errors.HasWarnings)
            {
                // TODO: tell the user about the warnings, might want to prompt them if they want to continue
                // runnning the "script"
            }

            return result.CompiledAssembly;
        }
Beispiel #52
0
        private static string CompileString(string csharpCode, string outFile) {
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters {
                OutputAssembly = outFile,
                GenerateExecutable = false,
                GenerateInMemory = false
            };
            parameters.ReferencedAssemblies.Add(typeof(ExportAttribute).Assembly.Location);
            parameters.ReferencedAssemblies.Add(typeof(IPythonInterpreterFactoryProvider).Assembly.Location);
            var result = provider.CompileAssemblyFromSource(parameters, csharpCode);
            if (result.Errors.HasErrors) {
                foreach (var err in result.Errors) {
                    Console.WriteLine(err);
                }
            }

            if (!File.Exists(outFile)) {
                Assert.Fail("Failed to compile {0}", outFile);
            }
            _tempFiles.Add(outFile);
            return outFile;
        }
Beispiel #53
0
        public static CompilerResults CompileFromSource(string source, bool generateInMemory = true)
        {
            CompilerParameters parameters = new CompilerParameters()
            {
                TempFiles = new TempFileCollection(".", false),
                GenerateInMemory = generateInMemory,
                TreatWarningsAsErrors = true,
            };

            foreach (string location in AppDomain.CurrentDomain.GetAssemblies().
                Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location)).
                Select(a => a.Location))
            {
                if (!parameters.ReferencedAssemblies.Contains(location))
                {
                    parameters.ReferencedAssemblies.Add(location);
                }
            }

            using (CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                return provider.CompileAssemblyFromSource(parameters, source);
            }
        }
Beispiel #54
0
        public Assembly compileSourceCode_Sync(string sourceCode)
        {
            if (sourceCode.notValid())
                return null;
            try
            {
                Environment.CurrentDirectory = PublicDI.config.CurrentExecutableDirectory;
                CompiledAssembly = null;
                beforeCompile.invoke();
                DebugMode.ifInfo("Compiling Source Code (Size: {0})", sourceCode.size());
                SourceCode = sourceCode;

                if (sourceCode.lines().starting("//CLR_3.5").notEmpty()) // allow setting compilation into 2.0 CLR
                {
                    CompilationVersion = "v3.5";
                }

                var providerOptions = new Dictionary<string, string>().add("CompilerVersion", CompilationVersion);

                var csharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions);
                var compilerParams = new CompilerParameters();
                compilerParams.OutputAssembly = "_o2_Script.dll".tempFile();
                compilerParams.IncludeDebugInformation = generateDebugSymbols;
                compilerParams.GenerateInMemory = !generateDebugSymbols;

                foreach (var referencedAssembly in ReferencedAssemblies)
                    compilerParams.ReferencedAssemblies.Add(referencedAssembly);

                CompilerResults = (generateDebugSymbols)
                                      ? csharpCodeProvider.CompileAssemblyFromFile(compilerParams,
                                                                                   sourceCode.saveWithExtension(".cs"))
                                      : csharpCodeProvider.CompileAssemblyFromSource(compilerParams, sourceCode);

                if (CompilerResults.Errors.Count > 0 || CompilerResults.CompiledAssembly == null)
                {
                    CompilationErrors = "";
                    foreach (CompilerError error in CompilerResults.Errors)
                    {
                        //CompilationErrors.Add(CompilationErrors.line(error.ToString());
                        var errorMessage = String.Format("{0}::{1}::{2}::{3}::{4}", error.Line,
                                                         error.Column, error.ErrorNumber,
                                                         error.ErrorText, error.FileName);
                        CompilationErrors = CompilationErrors.line(errorMessage);
                        "[CSharp_FastCompiler] Compilation Error: {0}".error(errorMessage);
                    }
                    DebugMode.ifError("Compilation failed");
                    onCompileFail.invoke();
                }
                else
                {
                    CompiledAssembly = CompilerResults.CompiledAssembly;
                    if (CompiledAssembly.Location.fileExists())
                        CompileEngine.setCachedCompiledAssembly_toMD5(sourceCode, CompiledAssembly);
                    DebugMode.ifDebug("Compilation was OK");
                    onCompileOK.invoke();
                }
                return CompiledAssembly;
            }
            catch (Exception ex)
            {
                ex.log("[compileSourceCode_Sync");
                return null;
            }
        }
        public ASLMethod(string code)
        {
            IsEmpty = string.IsNullOrWhiteSpace(code);
            code = code.Replace("return;", "return null;"); // hack

            using (var provider =
                new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }))
            {
                string source = $@"
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using LiveSplit.ComponentUtil;
using LiveSplit.Model;
public class CompiledScript
{{
    public string version;
    public double refreshRate;
    void print(string s)
    {{
        Trace.WriteLine(s);
    }}
    public dynamic Execute(LiveSplitState timer, dynamic old, dynamic current, dynamic vars, Process game)
    {{
        var memory = game;
        var modules = game.ModulesWow64Safe();
	    { code }
	    return null;
    }}
}}";

                var parameters = new System.CodeDom.Compiler.CompilerParameters()
                    {
                        GenerateInMemory = true,
                        CompilerOptions = "/optimize /d:TRACE",
                    };
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Data.dll");
                parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
                parameters.ReferencedAssemblies.Add("System.Drawing.dll");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
                parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
                parameters.ReferencedAssemblies.Add("LiveSplit.Core.dll");

                var res = provider.CompileAssemblyFromSource(parameters, source);

                if (res.Errors.HasErrors)
                {
                    var errorMessage = "";
                    foreach (var error in res.Errors)
                    {
                        errorMessage += error + "\r\n";
                    }
                    throw new ArgumentException(errorMessage, "code");
                }

                var type = res.CompiledAssembly.GetType("CompiledScript");
                CompiledCode = Activator.CreateInstance(type);
            }
        }
        private void _SaveSfxStub(string exeToGenerate, SelfExtractorSaveOptions options)
        {
            string nameOfIconFile = null;
            string stubExe = null;
            string unpackedResourceDir = null;
            string tmpDir = null;
            try
            {
                if (File.Exists(exeToGenerate))
                {
                    if (Verbose) StatusMessageTextWriter.WriteLine("The existing file ({0}) will be overwritten.", exeToGenerate);
                }
                if (!exeToGenerate.EndsWith(".exe"))
                {
                    if (Verbose) StatusMessageTextWriter.WriteLine("Warning: The generated self-extracting file will not have an .exe extension.");
                }

                // workitem 10553
                tmpDir = TempFileFolder ?? Path.GetDirectoryName(exeToGenerate);
                stubExe = GenerateTempPathname(tmpDir, "exe");

                // get the Ionic.Zip assembly
                Assembly a1 = typeof(ZipFile).Assembly;

                using (var csharp = new Microsoft.CSharp.CSharpCodeProvider
                       (new Dictionary<string,string>() { { "CompilerVersion", "v2.0" } })) {

                    // The following is a perfect opportunity for a linq query, but
                    // I cannot use it.  DotNetZip needs to run on .NET 2.0,
                    // and using LINQ would break that. Here's what it would look
                    // like:
                    //
                    //   var settings = (from x in SettingsList
                    //                   where x.Flavor == flavor
                    //                   select x).First();

                    ExtractorSettings settings = null;
                    foreach (var x in SettingsList)
                    {
                        if (x.Flavor == options.Flavor)
                        {
                            settings = x;
                            break;
                        }
                    }

                    // sanity check; should never happen
                    if (settings == null)
                        throw new BadStateException(String.Format("While saving a Self-Extracting Zip, Cannot find that flavor ({0})?", options.Flavor));

                    // This is the list of referenced assemblies.  Ionic.Zip is
                    // needed here.  Also if it is the winforms (gui) extractor, we
                    // need other referenced assemblies, like
                    // System.Windows.Forms.dll, etc.
                    var cp = new System.CodeDom.Compiler.CompilerParameters();
                    cp.ReferencedAssemblies.Add(a1.Location);
                    if (settings.ReferencedAssemblies != null)
                        foreach (string ra in settings.ReferencedAssemblies)
                            cp.ReferencedAssemblies.Add(ra);

                    cp.GenerateInMemory = false;
                    cp.GenerateExecutable = true;
                    cp.IncludeDebugInformation = false;
                    cp.CompilerOptions = "";

                    Assembly a2 = Assembly.GetExecutingAssembly();

                    // Use this to concatenate all the source code resources into a
                    // single module.
                    var sb = new System.Text.StringBuilder();

                    // In case there are compiler errors later, we allocate a source
                    // file name now. If errors are detected, we'll spool the source
                    // code as well as the errors (in comments) into that filename,
                    // and throw an exception with the filename.  Makes it easier to
                    // diagnose.  This should be rare; most errors happen only
                    // during devlpmt of DotNetZip itself, but there are rare
                    // occasions when they occur in other cases.
                    string sourceFile = GenerateTempPathname(tmpDir, "cs");


                    // // debugging: enumerate the resources in this assembly
                    // Console.WriteLine("Resources in this assembly:");
                    // foreach (string rsrc in a2.GetManifestResourceNames())
                    //   {
                    //     Console.WriteLine(rsrc);
                    //   }
                    // Console.WriteLine();


                    // all the source code is embedded in the DLL as a zip file.
                    using (ZipFile zip = ZipFile.Read(a2.GetManifestResourceStream("Ionic.Zip.Resources.ZippedResources.zip")))
                    {
                        // // debugging: enumerate the files in the embedded zip
                        // Console.WriteLine("Entries in the embbedded zip:");
                        // foreach (ZipEntry entry in zip)
                        //   {
                        //     Console.WriteLine(entry.FileName);
                        //   }
                        // Console.WriteLine();

                        unpackedResourceDir = GenerateTempPathname(tmpDir, "tmp");

                        if (String.IsNullOrEmpty(options.IconFile))
                        {
                            // Use the ico file that is embedded into the Ionic.Zip
                            // DLL itself.  To do this we must unpack the icon to
                            // the filesystem, in order to specify it on the cmdline
                            // of csc.exe.  This method will remove the unpacked
                            // file later.
                            System.IO.Directory.CreateDirectory(unpackedResourceDir);
                            ZipEntry e = zip["zippedFile.ico"];
                            // Must not extract a readonly file - it will be impossible to
                            // delete later.
                            if ((e.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                                e.Attributes ^= FileAttributes.ReadOnly;
                            e.Extract(unpackedResourceDir);
                            nameOfIconFile = Path.Combine(unpackedResourceDir, "zippedFile.ico");
                            cp.CompilerOptions += String.Format("/win32icon:\"{0}\"", nameOfIconFile);
                        }
                        else
                            cp.CompilerOptions += String.Format("/win32icon:\"{0}\"", options.IconFile);

                        cp.OutputAssembly = stubExe;

                        if (options.Flavor == SelfExtractorFlavor.WinFormsApplication)
                            cp.CompilerOptions += " /target:winexe";

                        if (!String.IsNullOrEmpty(options.AdditionalCompilerSwitches))
                            cp.CompilerOptions += " " + options.AdditionalCompilerSwitches;

                        if (String.IsNullOrEmpty(cp.CompilerOptions))
                            cp.CompilerOptions = null;

                        if ((settings.CopyThroughResources != null) && (settings.CopyThroughResources.Count != 0))
                        {
                            if (!Directory.Exists(unpackedResourceDir)) System.IO.Directory.CreateDirectory(unpackedResourceDir);
                            foreach (string re in settings.CopyThroughResources)
                            {
                                string filename = Path.Combine(unpackedResourceDir, re);

                                ExtractResourceToFile(a2, re, filename);
                                // add the file into the target assembly as an embedded resource
                                cp.EmbeddedResources.Add(filename);
                            }
                        }

                        // add the Ionic.Utils.Zip DLL as an embedded resource
                        cp.EmbeddedResources.Add(a1.Location);

                        // file header
                        sb.Append("// " + Path.GetFileName(sourceFile) + "\n")
                            .Append("// --------------------------------------------\n//\n")
                            .Append("// This SFX source file was generated by DotNetZip ")
                            .Append(ZipFile.LibraryVersion.ToString())
                            .Append("\n//         at ")
                            .Append(System.DateTime.Now.ToString("yyyy MMMM dd  HH:mm:ss"))
                            .Append("\n//\n// --------------------------------------------\n\n\n");

                        // assembly attributes
                        if (!String.IsNullOrEmpty(options.Description))
                            sb.Append("[assembly: System.Reflection.AssemblyTitle(\""
                                      + options.Description.Replace("\"", "")
                                      + "\")]\n");
                        else
                            sb.Append("[assembly: System.Reflection.AssemblyTitle(\"DotNetZip SFX Archive\")]\n");

                        if (!String.IsNullOrEmpty(options.ProductVersion))
                            sb.Append("[assembly: System.Reflection.AssemblyInformationalVersion(\""
                                      + options.ProductVersion.Replace("\"", "")
                                      + "\")]\n");

                        // workitem
                        string copyright =
                            (String.IsNullOrEmpty(options.Copyright))
                            ? "Extractor: Copyright © Dino Chiesa 2008-2011"
                            : options.Copyright.Replace("\"", "");

                        if (!String.IsNullOrEmpty(options.ProductName))
                            sb.Append("[assembly: System.Reflection.AssemblyProduct(\"")
                                .Append(options.ProductName.Replace("\"", ""))
                                .Append("\")]\n");
                        else
                            sb.Append("[assembly: System.Reflection.AssemblyProduct(\"DotNetZip\")]\n");


                        sb.Append("[assembly: System.Reflection.AssemblyCopyright(\"" + copyright + "\")]\n")
                            .Append(String.Format("[assembly: System.Reflection.AssemblyVersion(\"{0}\")]\n", ZipFile.LibraryVersion.ToString()));
                        if (options.FileVersion != null)
                            sb.Append(String.Format("[assembly: System.Reflection.AssemblyFileVersion(\"{0}\")]\n",
                                                    options.FileVersion.ToString()));

                        sb.Append("\n\n\n");

                        // Set the default extract location if it is available
                        string extractLoc = options.DefaultExtractDirectory;
                        if (extractLoc != null)
                        {
                            // remove double-quotes and replace slash with double-slash.
                            // This, because the value is going to be embedded into a
                            // cs file as a quoted string, and it needs to be escaped.
                            extractLoc = extractLoc.Replace("\"", "").Replace("\\", "\\\\");
                        }

                        string postExCmdLine = options.PostExtractCommandLine;
                        if (postExCmdLine != null)
                        {
                            postExCmdLine = postExCmdLine.Replace("\\", "\\\\");
                            postExCmdLine = postExCmdLine.Replace("\"", "\\\"");
                        }


                        foreach (string rc in settings.ResourcesToCompile)
                        {
                            using (Stream s = zip[rc].OpenReader())
                            {
                                if (s == null)
                                    throw new ZipException(String.Format("missing resource '{0}'", rc));
                                using (StreamReader sr = new StreamReader(s))
                                {
                                    while (sr.Peek() >= 0)
                                    {
                                        string line = sr.ReadLine();
                                        if (extractLoc != null)
                                            line = line.Replace("@@EXTRACTLOCATION", extractLoc);

                                        line = line.Replace("@@REMOVE_AFTER_EXECUTE", options.RemoveUnpackedFilesAfterExecute.ToString());
                                        line = line.Replace("@@QUIET", options.Quiet.ToString());
                                        if (!String.IsNullOrEmpty(options.SfxExeWindowTitle))

                                            line = line.Replace("@@SFX_EXE_WINDOW_TITLE", options.SfxExeWindowTitle);

                                        line = line.Replace("@@EXTRACT_EXISTING_FILE", ((int)options.ExtractExistingFile).ToString());

                                        if (postExCmdLine != null)
                                            line = line.Replace("@@POST_UNPACK_CMD_LINE", postExCmdLine);

                                        sb.Append(line).Append("\n");
                                    }
                                }
                                sb.Append("\n\n");
                            }
                        }
                    }

                    string LiteralSource = sb.ToString();

#if DEBUGSFX
                    // for debugging only
                    string sourceModule = GenerateTempPathname(tmpDir, "cs");
                    using (StreamWriter sw = File.CreateText(sourceModule))
                    {
                        sw.Write(LiteralSource);
                    }
                    Console.WriteLine("source: {0}", sourceModule);
#endif

                    var cr = csharp.CompileAssemblyFromSource(cp, LiteralSource);


                    if (cr == null)
                        throw new SfxGenerationException("Cannot compile the extraction logic!");

                    if (Verbose)
                        foreach (string output in cr.Output)
                            StatusMessageTextWriter.WriteLine(output);

                    if (cr.Errors.Count != 0)
                    {
                        using (TextWriter tw = new StreamWriter(sourceFile))
                        {
                            // first, the source we compiled
                            tw.Write(LiteralSource);

                            // now, append the compile errors
                            tw.Write("\n\n\n// ------------------------------------------------------------------\n");
                            tw.Write("// Errors during compilation: \n//\n");
                            string p = Path.GetFileName(sourceFile);

                            foreach (System.CodeDom.Compiler.CompilerError error in cr.Errors)
                            {
                                tw.Write(String.Format("//   {0}({1},{2}): {3} {4}: {5}\n//\n",
                                                       p,                                   // 0
                                                       error.Line,                          // 1
                                                       error.Column,                        // 2
                                                       error.IsWarning ? "Warning" : "error",   // 3
                                                       error.ErrorNumber,                   // 4
                                                       error.ErrorText));                  // 5
                            }
                        }
                        throw new SfxGenerationException(String.Format("Errors compiling the extraction logic!  {0}", sourceFile));
                    }

                    OnSaveEvent(ZipProgressEventType.Saving_AfterCompileSelfExtractor);

                    // Now, copy the resulting EXE image to the _writestream.
                    // Because this stub exe is being saved first, the effect will be to
                    // concatenate the exe and the zip data together.
                    using (System.IO.Stream input = System.IO.File.OpenRead(stubExe))
                    {
                        byte[] buffer = new byte[4000];
                        int n = 1;
                        while (n != 0)
                        {
                            n = input.Read(buffer, 0, buffer.Length);
                            if (n != 0)
                                WriteStream.Write(buffer, 0, n);
                        }
                    }
                }

                OnSaveEvent(ZipProgressEventType.Saving_AfterSaveTempArchive);
            }
            finally
            {
                try
                {
                    if (Directory.Exists(unpackedResourceDir))
                    {
                        try { Directory.Delete(unpackedResourceDir, true); }
                        catch (System.IO.IOException exc1)
                        {
                            StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exc1);
                        }
                    }
                    if (File.Exists(stubExe))
                    {
                        try { File.Delete(stubExe); }
                        catch (System.IO.IOException exc1)
                        {
                            StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exc1);
                        }
                    }
                }
                catch (System.IO.IOException) { }
            }

            return;

        }
Beispiel #57
0
		/// <summary>
		/// Does the compilation of the script into an assembly. The assembly is stored together with
		/// the read-only source code and returned as result. As list of compiled source codes is maintained by this class.
		/// If you provide a text that was already compiled before, the already compiled assembly is returned instead
		/// of a freshly compiled assembly.
		/// </summary>
		/// <returns>True if successfully compiles, otherwise false.</returns>
		public static IScriptCompilerResult Compile(string[] scriptText, out string[] errors)
		{
			ScriptCompilerResult result;

			string scriptTextHash = ScriptCompilerResult.ComputeScriptTextHash(scriptText);

			if (_compilerResults.TryGetValue(scriptTextHash, out result))
			{
				errors = null;
				return result;
			}

			Dictionary<string, string> providerOptions = new Dictionary<string, string>();
			providerOptions.Add("CompilerVersion", "v4.0");
			Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions);

			// For Visual Basic Compiler try this :
			//Microsoft.VisualBasic.VBCodeProvider

			System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();

			parameters.GenerateInMemory = true;
			parameters.IncludeDebugInformation = true;
			// parameters.OutputAssembly = this.ScriptName;

			// Add available assemblies including the application itself
			foreach (string loc in Settings.Scripting.ReferencedAssemblies.AllLocations)
				parameters.ReferencedAssemblies.Add(loc);

			CompilerResults results;
			if (scriptText.Length == 1)
				results = codeProvider.CompileAssemblyFromSource(parameters, scriptText[0]);
			else
				results = codeProvider.CompileAssemblyFromSource(parameters, scriptText);

			if (results.Errors.Count > 0)
			{
				errors = new string[results.Errors.Count];
				int i = 0;
				foreach (CompilerError err in results.Errors)
				{
					errors[i++] = err.ToString();
				}

				return null;
			}
			else
			{
				result = new ScriptCompilerResult(scriptText, scriptTextHash, results.CompiledAssembly);
				_compilerResults.TryAdd(result);
				errors = null;
				return result;
			}
		}
        private static Assembly CompileAssembly(Template template, TemplateCompilation compilation)
        {
            string source = compilation.SourceCode;
            Assembly cachedAssembly = TemplateExpressionAssemblyCache.GetAssembly(source);
            if (cachedAssembly != null)
                return cachedAssembly;

            CompilerParameters config = new CompilerParameters() { GenerateInMemory = true };
            foreach (string asmName in template.ReferencedAssemblies)
                config.ReferencedAssemblies.Add(asmName);

            if (!config.ReferencedAssemblies.Contains("FistCore.Generator.TemplateEngine.dll"))
                config.ReferencedAssemblies.Add("FistCore.Generator.TemplateEngine.dll");

            if (!config.ReferencedAssemblies.Contains("FistCore.Core.dll"))
                config.ReferencedAssemblies.Add("FistCore.Core.dll");

            Dictionary<string, string> options = new Dictionary<string, string>();
            options["CompilerVersion"] = "v3.5";
            Microsoft.CSharp.CSharpCodeProvider compiler = new Microsoft.CSharp.CSharpCodeProvider(options);
            //CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
            // All referenced assemblies must be in the same directory as entry assembly.
            string oldCwd = Directory.GetCurrentDirectory();
            Directory.SetCurrentDirectory(IoUtil.GetExecutableDirectory());
            CompilerResults output = compiler.CompileAssemblyFromSource(config, source);
            Directory.SetCurrentDirectory(oldCwd);
            if (output.Errors.HasErrors)
            {
                SetCompilerErrors(compilation, output.Errors);
                string errmsg = compilation.GetCompilationErrorsDescription();
                throw new Exception(template.Header.Title + Environment.NewLine + errmsg);
            }

            TemplateExpressionAssemblyCache.SetAssembly(source, output.CompiledAssembly);
            return output.CompiledAssembly;
        }
Beispiel #59
0
 public static CompilerResults Compile(string[] filenames, OutputType ot, string outfile)
 {
     //Generate Parameters and Code Provider
     Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
     CompilerParameters param = new CompilerParameters();
     param.GenerateInMemory = false;
     param.IncludeDebugInformation = true;
     param.GenerateExecutable=ot == OutputType.Dll ? false : true;
     param.OutputAssembly = outfile;
     param.EmbeddedResources.Add("SharpLua.dll");
     param.ReferencedAssemblies.Add("SharpLua.dll");
     string classname2 =(new System.Random(DateTime.Now.Millisecond)).Next().ToString();
     switch (ot)
     {
         case OutputType.Dll:
             param.CompilerOptions = "/target:library";
             break;
         case OutputType.Exe:
             param.CompilerOptions = "/target:exe";
             break;
         case OutputType.WinFormsExe:
             param.CompilerOptions = "/target:winexe";
             break;
         default:
             param.CompilerOptions = "/target:exe";
             break;
     }
     param.MainClass = "SharpLua.ClassName" + classname2;
     
     // Generate SharpLua Code
     string SharpLuaScript = GetLSScript();
     SharpLuaScript = SharpLuaScript.Replace("{ClassName}", "ClassName" + classname2);
     string ActualSharpLuaCode ="";
     foreach (string filename in filenames)
     {
         try {
             ActualSharpLuaCode += System.IO.File.ReadAllText(filename);
         } catch {
             
         }
         // Attempt basic parsing.
         try
         {
             Parser.Parser p = new SharpLua.Parser.Parser();
             bool s;
             p.ParseChunk(new Parser.TextInput(ActualSharpLuaCode), out s);
         } catch (Exception e) {
             Console.WriteLine("Parsing Error: " + e.ToString());
             return null;
         }
         
         // Compiling
         ActualSharpLuaCode = ActualSharpLuaCode.Replace("\\", "\\\\");
         ActualSharpLuaCode = ActualSharpLuaCode.Replace("\"", "\\\"");
         string[] codes  = ActualSharpLuaCode.Split(new string[] {"\n"}, StringSplitOptions.None);
         string newcodes = "";
         for (int i = 0; i < codes.Length; i++)
             newcodes += "\"" + codes[i].Replace("\n","").Replace("\r","") + "\",";
         
         if (newcodes.EndsWith(","))
             newcodes = newcodes.Substring(0, newcodes.Length -1);
         SharpLuaScript = SharpLuaScript.Replace("|insertcodehere|", newcodes);
         System.IO.File.WriteAllText(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filename), System.IO.Path.GetFileNameWithoutExtension(filename) + ".cs"), SharpLuaScript);
     }
     // Compile and return the results
     CompilerResults results= csharp.CompileAssemblyFromSource(param, SharpLuaScript);
     return results;
 }
Beispiel #60
0
        public RunResults RunExternal()
        {
            // Set up compiler parameters.
            CompilerParameters cp = new CompilerParameters();
            AddReferenceLibraries(cp);
            cp.GenerateExecutable = true;
            cp.OutputAssembly = "Temp.exe";
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;

            // Compile sources.
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, this.ToString());
            if (cr.Errors.Count > 0)
                return AppropriateErrorResult(cr);

            // Run test in separate process.
            Process p = new Process();
            p.StartInfo.FileName = RandoopEnvironment.Instance.MiniDHandler;
            p.StartInfo.RedirectStandardOutput = true;
            StringBuilder arguments = new StringBuilder();
            arguments.Append("/O:\"C:\\foobar.txt\"");
            arguments.Append(" /I:" + "\"" + RandoopEnvironment.Instance.DefaultDhi + "\"");
            arguments.Append(" /App:\"Temp\"");
            p.StartInfo.Arguments = arguments.ToString();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.ErrorDialog = true;
            p.StartInfo.CreateNoWindow = false;

            p.Start();
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit(10000);

            // Exit code 100 means behavior was reproduced.
            if (p.ExitCode != 100)
            {
                return RunResults.CompiledOKBehaviorNotReproduced();
            }
            return RunResults.CompiledOKBehaviorWasReproduced();
        }