Пример #1
0
        /// <summary>
        /// 编译此类并创建为程序集
        /// </summary>
        public void SaveAssembly()
        {
            // 创建一个Assembly对象
            _myAssembly = new CodeCompileUnit();
            // 将命名空间添加到程序集
            _myAssembly.Namespaces.Add(_myNameSpace);
            // 添加如下的编译参数
            var comParam = new CompilerParameters(new string[] { "mscorlib.dll" });

            comParam.ReferencedAssemblies.Add("System.dll");
            comParam.ReferencedAssemblies.Add("System.Drawing.dll");
            comParam.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            // 标识编译器是否需要输出到内存
            comParam.GenerateInMemory = false;
            // 标识输出是否可以执行
            comParam.GenerateExecutable = true;
            // 提供有入口函数Main的类的名字
            comParam.MainClass = "MyNamespace.MyClass";
            // 生成的程序集存在的位置, 同名会替换
            comParam.OutputAssembly = @"C:\Users\HeabK\Desktop\dotnetConsole.exe";
            // 创建C#编译器实例, 将此Assembly对象传递进去
            var           ccp = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler icc = ccp.CreateCompiler();
            // CompileAssemblyFromDom 会返回错误列表(如果有)或创建的各个程序集的路径
            var compres = icc.CompileAssemblyFromDom(comParam, _myAssembly);

            if (compres.Errors.Count > 0)
            {
                compres.Errors.Cast <object>().ToList().ForEach(Console.WriteLine);
            }
            else
            {
            }
        }
Пример #2
0
        private Type CompileClass(ClassBuilder classBuilder)
        {
            List <string> errorMessages = new List <string>();

            string source = classBuilder.ToString();

            Microsoft.CSharp.CSharpCodeProvider cp
                = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler      ic = cp.CreateCompiler();
            System.CodeDom.Compiler.CompilerParameters cpar
                = new System.CodeDom.Compiler.CompilerParameters();
            cpar.GenerateInMemory   = true;
            cpar.GenerateExecutable = false;
            foreach (string reference in References)
            {
                cpar.ReferencedAssemblies.Add(reference);
            }

            System.CodeDom.Compiler.CompilerResults cr
                = ic.CompileAssemblyFromSource(cpar, source);

            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                errorMessages.Add(ce.ErrorText);
            }

            if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
            {
                return(cr.CompiledAssembly.GetType(classBuilder.FullName));
            }

            throw new ApplicationException("Compiler error"); // assemble error messages here
        }
        // http://www.codeproject.com/KB/cs/runtimecompiling.aspx
        private static System.Reflection.Assembly BuildAssembly(string code)
        {
            Microsoft.CSharp.CSharpCodeProvider provider =
                new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler      compiler       = provider.CreateCompiler();
            System.CodeDom.Compiler.CompilerParameters compilerparams = new System.CodeDom.Compiler.CompilerParameters();

            string strLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string strBasePath = System.IO.Path.GetDirectoryName(strLocation);

            string strSerializationTypes  = System.IO.Path.Combine(strBasePath, "SerializationTypes.dll");
            string strFileHelpersLocation = System.IO.Path.Combine(strBasePath, "FileHelpers.dll");

            compilerparams.ReferencedAssemblies.Add(strSerializationTypes);
            compilerparams.ReferencedAssemblies.Add(strFileHelpersLocation);

            compilerparams.GenerateExecutable = false;
            compilerparams.GenerateInMemory   = true;
            System.CodeDom.Compiler.CompilerResults results =
                compiler.CompileAssemblyFromSource(compilerparams, code);
            if (results.Errors.HasErrors)
            {
                System.Text.StringBuilder errors = new System.Text.StringBuilder("Compiler Errors :\r\n");
                foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
                {
                    errors.AppendFormat("Line {0},{1}\t: {2}\n",
                                        error.Line, error.Column, error.ErrorText);
                }
                throw new Exception(errors.ToString());
            }
            else
            {
                return(results.CompiledAssembly);
            }
        }     // End Function BuildAssembly
        public void SaveAssembly()
        {
            myassembly = new CodeCompileUnit();
            myassembly.Namespaces.Add(mynamespace);
            CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll" });

            comparam.ReferencedAssemblies.Add("System.dll");
            comparam.GenerateInMemory   = false;
            comparam.GenerateExecutable = true;
            comparam.MainClass          = "mynamespace.Myclass";
            comparam.OutputAssembly     = @"c:\temp\HelloWorld.exe";
            Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();
            StreamWriter sw = new StreamWriter(@"c:\temp\HelloWorld.cs");
            // ez is jo:
            // IndentedTextWriter
            // ???
            IndentedTextWriter idt = new IndentedTextWriter(sw, " ");

            idt.Indent = 1;
            ICodeGenerator  cscg    = ccp.CreateGenerator(idt);
            ICodeCompiler   icc     = ccp.CreateCompiler();
            CompilerResults compres = icc.CompileAssemblyFromDom(comparam, myassembly);

            cscg.GenerateCodeFromNamespace(mynamespace, idt, new CodeGeneratorOptions());
            idt.Close();
            if (compres == null || compres.Errors.Count > 0)
            {
                for (int i = 0; i < compres.Errors.Count; i++)
                {
                    Console.WriteLine(compres.Errors[i]);
                }
            }
        }
Пример #5
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);
        }
Пример #6
0
        public static object UploadData(string url, string @namespace, string classname,
                                        string methodname, object[] args, ArrayList al)
        {
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                //System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
                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, string.Empty, string.Empty);                 //将sd描述导入到sdi中
                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.ICodeCompiler icc = csc.CreateCompiler();

                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 = icc.CompileAssemblyFromDom(cplist, ccu);
                if (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);

                ParameterModifier[] paramsModifer = new ParameterModifier[1];
                paramsModifer[0] = new ParameterModifier(args.Length);
                //paramsModifer[0][7] = true;

                object result = t.InvokeMember(methodname, BindingFlags.Default | BindingFlags.InvokeMethod, null,
                                               obj, args, paramsModifer, null, null);

                //al.Add(args[7]);
                return(result);
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, EXCEPTION_LOG_TITLE);
                return(null);
            }
        }
Пример #7
0
        /// <summary>
        /// 根据指定的信息,调用远程WebService方法
        /// </summary>
        /// <param name="url">WebService的http形式的地址</param>
        /// <param name="namespace">欲调用的WebService的命名空间</param>
        /// <param name="classname">欲调用的WebService的类名(不包括命名空间前缀)</param>
        /// <param name="methodname">欲调用的WebService的方法名</param>
        /// <param name="args">参数列表</param>
        /// <returns>WebService的执行结果</returns>
        /// <remarks>
        /// 如果调用失败,将会抛出Exception。请调用的时候,适当截获异常。
        /// 异常信息可能会发生在两个地方:
        /// 1、动态构造WebService的时候,CompileAssembly失败。
        /// 2、WebService本身执行失败。
        /// </remarks>
        /// <example>
        /// <code>
        /// object obj = InvokeWebService("http://localhost/Service.asmx","method",new object[]{"1"});
        /// </code>
        /// </example>
        public static object InvokeWebService(string url, string methodname, object[] args)
        {
            try
            {
                string               @namespace = "WebService.DynamicWebCalling";
                string[]             parts      = url.Split('/');
                string[]             pps        = parts[parts.Length - 1].Split('.');
                string               classname  = pps[0];
                System.Net.WebClient wc         = new System.Net.WebClient();
                System.IO.Stream     stream     = wc.OpenRead(url + "?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(@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.ICodeCompiler icc = csc.CreateCompiler();

                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 = 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)
            {
                StringBuilder str = new StringBuilder();
                for (int m = 0; m < args.Length; m++)
                {
                    str.Append(args[m]);
                    str.Append(",");
                }
                LogUtility.DataLog.WriteLog(LogUtility.LogLevel.Info, ex.Message + "--" + ex.Source.ToString() + "--" + url + methodname + "--" + str, new LogUtility.RunningPlace("WebServiceHelper", "InvokeWebService"), "WebService获取数据失败");
                return("");
            }
        }
Пример #8
0
        private object InvokeWebservice(string url, string space, string classname, string methodname, object[] args)
        {
            try
            {
                System.Net.WebClient wc     = new System.Net.WebClient();
                System.IO.Stream     stream = wc.OpenRead(url + "?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(space);
                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.ICodeCompiler icc = csc.CreateCompiler();

                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 = 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(space + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                //用来解决webservice上面有重载函数的问题
                Type[] types = new Type[args.Length];
                for (int i = 0; i < args.Length; i++)
                {
                    types[i] = args[i].GetType();
                }
                System.Reflection.MethodInfo mi = t.GetMethod(methodname, types);
                if (null == mi)
                {
                    return(null);
                }
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Пример #9
0
        private static Assembly Compile(string[] files)
        {
            errors = new List <System.CodeDom.Compiler.CompilerError>();

            Microsoft.CSharp.CSharpCodeProvider provider;
            Dictionary <string, string>         param = new Dictionary <string, string>();

            param.Add("CompilerVersion", "v4.0");
            provider = new Microsoft.CSharp.CSharpCodeProvider(param);
            System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();

            options.GenerateInMemory        = true;
            options.TreatWarningsAsErrors   = false;
            options.IncludeDebugInformation = true;

            List <string> refs = new List <string>();

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            for (int i = 0; i < assemblies.Length; i++)
            {
                if (!assemblies[i].FullName.Contains("System.") && !assemblies[i].FullName.Contains("Microsoft."))
                {
                    refs.Add(System.IO.Path.GetFileName(assemblies[i].Location));
                    //refs.Add(assemblies[i].Location);
                }
            }
            refs.Add("System.dll");
            refs.Add("System.Data.dll");
            refs.Add("System.Drawing.dll");
            refs.Add("System.Xml.dll");
            refs.Add("System.Windows.Forms.dll");
            //refs.Add("DatabaseConnector.dll");
            refs.Add("System.Core.dll");
            refs.Add("MySql.Data.dll");
            refs.Add("DataManager.dll");
            refs.Add("Server.RDungeons.dll");
            refs.Add(System.Windows.Forms.Application.ExecutablePath);
            options.ReferencedAssemblies.AddRange(refs.ToArray());

            System.CodeDom.Compiler.ICodeCompiler   compiler = provider.CreateCompiler();
            System.CodeDom.Compiler.CompilerResults results  = compiler.CompileAssemblyFromFileBatch(options, files);

            foreach (System.CodeDom.Compiler.CompilerError err in results.Errors)
            {
                errors.Add(err);
            }

            if (results.Errors.Count == 0)
            {
                return(results.CompiledAssembly);
            }
            else
            {
                return(null);
            }
        }
Пример #10
0
    public bool Intialize(string equation)
    {
        Microsoft.CSharp.CSharpCodeProvider        cp   = new Microsoft.CSharp.CSharpCodeProvider();
        System.CodeDom.Compiler.ICodeCompiler      comp = cp.CreateCompiler();
        System.CodeDom.Compiler.CompilerParameters cpar = new CompilerParameters();

        cpar.GenerateInMemory   = true;
        cpar.GenerateExecutable = false;
        cpar.ReferencedAssemblies.Add("system.dll");
        cpar.ReferencedAssemblies.Add("EquationsParser.exe");                   //Did you see this before;
        string sourceCode = "using System;" +
                            "class DrivedEval:EquationsParser.BaseClass" +
                            "{" +
                            "public DrivedEval(){}" +
                            "public override double Eval(double x,double y)" +
                            "{" +
                            "return " + /*Looook here code insertion*/ equation + ";" +
                            "}" +
                            "}";
        //the previouse source code will be compiled now(run time);
        CompilerResults result = comp.CompileAssemblyFromSource(cpar, sourceCode);
        //If there are error in the code display it for the programmer who enter the equation
        string errors = "";

        foreach (CompilerError rrr in result.Errors)
        {
            if (rrr.IsWarning)
            {
                continue;
            }
            errors += "\n" + rrr.ErrorText;
            errors += "\n" + rrr.ToString();
        }
        //You Can show error if there in the sourceCode you just compiled uncomment the following
        //MessageBox.Show(errors);
        if (result.Errors.Count == 0 && result.CompiledAssembly != null)
        {
            Type objtype = result.CompiledAssembly.GetType("DrivedEval");
            try
            {
                if (objtype != null)
                {
                    Evalulator = (BaseClass)Activator.CreateInstance(objtype);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error in Creation the object");
            }
            return(true);
        }
        else
        {
            return(false);
        }
    }
Пример #11
0
        internal Assembly Compile() {
            CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler compiler = codeProvider.CreateCompiler();
            CompilerParameters options = new CompilerParameters(Imports);

            options.WarningLevel = 1;
            options.TreatWarningsAsErrors = true;
            options.CompilerOptions = "/nowarn:183,184,602,612,626,672,679,1030,1200,1201,1202,1203,1522,1570,1574,1580,1581,1584,1589,1590,1592,1596,1598,1607,2002,2014,2023,3012,5000";
            
            if (CompModSwitches.KeepTempFiles.Enabled) {
                options.GenerateInMemory = false;
                options.IncludeDebugInformation = true;
                options.TempFiles = new TempFileCollection();
                options.TempFiles.KeepFiles = true;
            }
            else {
                options.GenerateInMemory = true;
            }

            PermissionSet perms = new PermissionSet(PermissionState.Unrestricted);
            perms.AddPermission(FileIOPermission);
            perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            perms.Assert();

            CompilerResults results = null;
            Assembly assembly = null;
            try {
                results = compiler.CompileAssemblyFromSource(options, writer.ToString());
                assembly = results.CompiledAssembly;
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }


            if (results.Errors.HasErrors) {
                StringWriter stringWriter = new StringWriter();
                stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString()));
                foreach (CompilerError e in results.Errors) {
                    // clear filename. This makes ToString() print just error number and message.
                    e.FileName = "";
                    stringWriter.WriteLine(e.ToString());
                }
                System.Diagnostics.Debug.WriteLine(stringWriter.ToString());
                throw new InvalidOperationException(stringWriter.ToString());
            }

            // somehow we got here without generating an assembly
            if (assembly == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));
            
            return assembly;
        }
    public void Eval(string Code)
    {
        Microsoft.CSharp.CSharpCodeProvider        Provider   = new Microsoft.CSharp.CSharpCodeProvider();        // Create an provider
        System.CodeDom.Compiler.ICodeCompiler      Compiler   = Provider.CreateCompiler();                        // Create An Compiler
        System.CodeDom.Compiler.CompilerParameters Parameters = new System.CodeDom.Compiler.CompilerParameters(); // Create a parameters of the compiler
        Parameters.GenerateInMemory = true;                                                                       // It should generate the compiled assembly in the memory
        System.CodeDom.Compiler.CompilerResults Results = Compiler.CompileAssemblyFromSource(Parameters, Code);   //Compile it
        ///Now you just need to use reflection to call its methods
        object SomeClass = Results.CompiledAssembly.CreateInstance("ClassName");                                  //Name of the class you want to create an instance
        var    Method    = SomeClass.GetType().GetMethod("MethodName");                                           //Name of the Method you want to call

        Method.Invoke(SomeClass, null);                                                                           // change null for the argument it needs
    }
Пример #13
0
        private static int InvokeWebservice(string url, string @namespace, string classname, string methodname, object[] args)
        {
            try
            {
                System.Net.WebClient wc     = new System.Net.WebClient();
                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.ICodeCompiler icc = csc.CreateCompiler();

                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 = 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);

                mi.Invoke(obj, args);
            }
            catch
            {
                return(-1);
            }

            return(1);
        }
Пример #14
0
        //public void SendMail(string mailTo, string mailSubject, string content)
        //{
        //    object[] methodParams = new object[4];
        //    methodParams[0] = new object();
        //    methodParams[1] = new object();
        //    methodParams[2] = new object();
        //    methodParams[3] = new object();
        //    methodParams[0] = mailTo;
        //    methodParams[1] = true;
        //    methodParams[2] = mailSubject;
        //    methodParams[3] = content;
        //    InvokeWebservice(ConfigData.MailURL, "Achievo.MMIP.CommonWebService", "EMail", "SendByAdmin", methodParams);
        //}
        /// 根据指定的信息,调用远程WebService方法
        /// </summary>
        /// <param name="url">WebService的http形式的地址</param>
        /// <param name="namespace">欲调用的WebService的命名空间</param>
        /// <param name="classname">欲调用的WebService的类名(不包括命名空间前缀)</param>
        /// <param name="methodname">欲调用的WebService的方法名</param>
        /// <param name="args">参数列表</param>
        /// <returns>WebService的执行结果</returns>
        /// <remarks>
        /// 如果调用失败,将会抛出Exception。请调用的时候,适当截获异常。
        /// 异常信息可能会发生在两个地方:
        /// 1、动态构造WebService的时候,CompileAssembly失败。
        /// 2、WebService本身执行失败。
        /// </remarks>
        /// <example>
        /// <code>
        /// object obj = InvokeWebservice("http://localhost/GSP_WorkflowWebservice/common.asmx",
        ///                               "Genersoft.Platform.Service.Workflow",
        ///                               "Common",
        ///                               "GetToolType",
        ///                               new object[]{"1"});
        /// </code>
        /// </example>
        public object InvokeWebservice(string url, string @namespace, string classname,
                                              string methodname, object[] args)
        {
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                System.IO.Stream stream = wc.OpenRead(url + "?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(@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.ICodeCompiler icc = csc.CreateCompiler();
                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 = 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));
            }
        }
Пример #15
0
		public TestCompiler( string[] assemblyNames, string outputName )
		{
			Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
			this.compiler = provider.CreateCompiler();
			this.options = new CompilerParameters();

			if ( assemblyNames != null && assemblyNames.Length > 0 )
				options.ReferencedAssemblies.AddRange( assemblyNames );
			if ( outputName != null )
				options.OutputAssembly = outputName;

			options.IncludeDebugInformation = false;
			options.TempFiles = new TempFileCollection( ".", false );
			options.GenerateInMemory = false;
		}
Пример #16
0
 protected virtual CompilerResults Compile(string code, Type[] types)
 {
     Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider ();
     ICodeCompiler compiler = provider.CreateCompiler ();
     ArrayList assemblies = new ArrayList ();
     assemblies.Add ("System.dll");
     foreach (Type type in types)
     {
         assemblies.Add (type.Assembly.Location);
     }
     string[] assemblyNames = (string[]) assemblies.ToArray (typeof (string));
     CompilerParameters options = new CompilerParameters (assemblyNames);
     options.GenerateInMemory = true;
     CompilerResults results = compiler.CompileAssemblyFromSource (options, code);
     return results;
 }
Пример #17
0
        /// <summary>
        /// Creates an assembly by dynamically compiling TestVersionTableMetaData.cs
        /// </summary>
        /// <returns></returns>
        private Assembly GetAssemblyWithCustomVersionTableMetaData()
        {
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler compiler = provider.CreateCompiler();
            CompilerParameters parms = new CompilerParameters();

            // Configure parameters
            parms.GenerateExecutable = false;
            parms.GenerateInMemory = true;
            parms.IncludeDebugInformation = false;
            parms.ReferencedAssemblies.Add("System.dll");
            parms.ReferencedAssemblies.Add("FluentMigrator.dll");

            CompilerResults results = compiler.CompileAssemblyFromFile(parms, "..\\..\\Unit\\TestVersionTableMetaData.cs");
            Assert.AreEqual(0, results.Errors.Count);
            return results.CompiledAssembly;
        }
Пример #18
0
		public TestCompiler( string[] assemblyNames, string outputName )
		{
			this.provider = new Microsoft.CSharp.CSharpCodeProvider();
#if !NET_2_0
			this.compiler = provider.CreateCompiler();
#endif
			this.options = new CompilerParameters();

			if ( assemblyNames != null && assemblyNames.Length > 0 )
				options.ReferencedAssemblies.AddRange( assemblyNames );
			if ( outputName != null )
				options.OutputAssembly = outputName;

			options.IncludeDebugInformation = false;
			options.TempFiles = new TempFileCollection( ".", false );
			options.GenerateInMemory = false;
		}
Пример #19
0
        }   //DynamicReport

        public void SaveAssembly(string rptname)
        {
            myassembly = new CodeCompileUnit();

            //namespace-ээ assembly -д оруулж байна
            myassembly.Namespaces.Add(mynamespace);

            //Ашиглагдах dll ээ оруулж ирж байна.(using...)
            CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll", "ISM.Template.dll" });

            comparam.ReferencedAssemblies.Add("System.dll");
            comparam.ReferencedAssemblies.Add("System.Drawing.dll");
            comparam.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            comparam.ReferencedAssemblies.Add("ISM.Template.dll");

            comparam.GenerateInMemory = false;
            comparam.EmbeddedResources.Add(rptname);
            comparam.GenerateExecutable = true;
            comparam.MainClass          = txtSlipsname.Text + ".Resource";
            //Үүсгэх газрыг зааж өгч байна.
            comparam.OutputAssembly = _core.SlipsPathIn + "\\" + txtSlipsname.Text + ".dll";
            Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler icc = ccp.CreateCompiler();

            //Ямар нэгэн алдаа гарвал мессэжбокс дээр хэвлэх үйлдэл явагдаж байна.
            CompilerResults compres = icc.CompileAssemblyFromDom(comparam, myassembly);

            if (compres == null || compres.Errors.Count > 0)
            {
                string error = "";
                for (int i = 0; i < compres.Errors.Count; i++)
                {
                    error = error + "\r\n" + compres.Errors[i].ToString();
                }
                MessageBox.Show(error);
                return;
            }
            else
            {
                MessageBox.Show("Амжилттай үүслээ.");
            }
        }                   //Slips
Пример #20
0
        /// <summary>
        /// Summary description for Class:cCharpEvaluateString
        /// </summary>
        static public object CSharpEvaluateToObject(string cCharpEvaluateString, out string ErrorString)
        {
            ErrorString = "";
            try
            {
                Microsoft.CSharp.CSharpCodeProvider        csharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.ICodeCompiler      compiler           = csharpCodeProvider.CreateCompiler();
                System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();
                cp.ReferencedAssemblies.Add("system.dll");
                cp.CompilerOptions  = "/t:library";
                cp.GenerateInMemory = true;

                StringBuilder sCode = new StringBuilder();
                sCode.Append("using System;");
                sCode.Append("namespace CoustomEvaluate{");
                sCode.Append("class A{public object Eval(){return (" + cCharpEvaluateString + ");}}");
                sCode.Append("}");

                System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromSource(cp, sCode.ToString());
                if (results.Errors.HasErrors)
                {
                    ErrorString = "Compiler Error:\r\n";
                    foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
                    {
                        ErrorString += "Error Line:" + error.Line + ", Column:" + error.Column + "\r\n";
                        ErrorString += "ErrorText:" + error.ErrorText + "\r\n";
                    }
                    return(null);
                }
                System.Reflection.Assembly assembly = results.CompiledAssembly;
                object Inst = assembly.CreateInstance("CoustomEvaluate.A");
                Type   type = Inst.GetType();
                System.Reflection.MethodInfo mi = type.GetMethod("Eval");
                return(mi.Invoke(Inst, null));
            }
            catch (Exception exp)
            {
                ErrorString = "CSharpEvaluateToObject Eror:" + exp.Message + "\r\nSource:" + cCharpEvaluateString;
                return(null);
            }
        }
Пример #21
0
        public MDynamicSupport GetImplementation()
        {
            // TODO: Adds a cache for generated assemblies...

            CodeNamespace ns = BuildMDynamicSupportCodeDom();

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

            cp.CreateGenerator().GenerateCodeFromNamespace(ns, Console.Out, null);

            CodeCompileUnit unit = new CodeCompileUnit();

            unit.Namespaces.Add(ns);

            String[] assembliesName = GetRequiredAssemblies();

            CompilerParameters parameters = new CompilerParameters(assembliesName);

            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory   = true;

            CompilerResults result =
                cp.CreateCompiler().CompileAssemblyFromDom(parameters, unit);

            if (result.Errors.HasErrors)
            {
                throw new CompilationException(result.Errors);
            }

            Type dynamicType =
                result.CompiledAssembly.GetType(
                    "Castle.ManagementExtensions.Generated.DynamicImplementation", true, true);

            Object inst = Activator.CreateInstance(
                dynamicType,
                new object[] { info, instance });

            return((MDynamicSupport)inst);
        }
Пример #22
0
        CompilerResults Compile(MigrationContext context, CodeCompileUnit dom)
        {
            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateInMemory = true;
            parameters.ReferencedAssemblies.Add(GetType().Assembly.Location);
            parameters.ReferencedAssemblies.Add(context.TargetAssembly.Location);

            if (_references.Length > 0)
            {
                foreach (string reference in _references.Split(';'))
                {
                    string assemblyName = reference.Trim();
                    parameters.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);
                }
            }

            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler   compiler = provider.CreateCompiler();

            return(compiler.CompileAssemblyFromDom(parameters, dom));
        }
		public MDynamicSupport GetImplementation()
		{
			// TODO: Adds a cache for generated assemblies...

			CodeNamespace ns = BuildMDynamicSupportCodeDom();

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

			cp.CreateGenerator().GenerateCodeFromNamespace( ns, Console.Out, null );

			CodeCompileUnit unit = new CodeCompileUnit();
			unit.Namespaces.Add( ns );

			String[] assembliesName = GetRequiredAssemblies(); 

			CompilerParameters parameters = new CompilerParameters(assembliesName);
			parameters.GenerateExecutable = false;
			parameters.GenerateInMemory   = true;

			CompilerResults result = 
				cp.CreateCompiler().CompileAssemblyFromDom(parameters, unit);

			if (result.Errors.HasErrors)
			{
				throw new CompilationException(result.Errors);
			}

			Type dynamicType = 
				result.CompiledAssembly.GetType(
					"Castle.ManagementExtensions.Generated.DynamicImplementation", true, true);

			Object inst = Activator.CreateInstance(
				dynamicType, 
				new object[] { info, instance } );

			return (MDynamicSupport) inst;
		}
Пример #24
0
        private static Assembly Compile(string[] files)
        {
            errors = new List<System.CodeDom.Compiler.CompilerError>();

            Microsoft.CSharp.CSharpCodeProvider provider;
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("CompilerVersion", "v4.0");
            provider = new Microsoft.CSharp.CSharpCodeProvider(param);
            System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();

            options.GenerateInMemory = true;
            options.TreatWarningsAsErrors = false;
            options.IncludeDebugInformation = true;

            List<string> refs = new List<string>();
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            for (int i = 0; i < assemblies.Length; i++) {
                if (!assemblies[i].FullName.Contains("System.") && !assemblies[i].FullName.Contains("Microsoft.")) {
                    refs.Add(System.IO.Path.GetFileName(assemblies[i].Location));
                    //refs.Add(assemblies[i].Location);

                }
            }
            refs.Add("System.dll");
            refs.Add("System.Data.dll");
            refs.Add("System.Drawing.dll");
            refs.Add("System.Xml.dll");
            refs.Add("System.Windows.Forms.dll");
            //refs.Add("DatabaseConnector.dll");
            refs.Add("System.Core.dll");
            refs.Add("MySql.Data.dll");
            refs.Add("DataManager.dll");
            refs.Add("Server.RDungeons.dll");
            refs.Add(System.Windows.Forms.Application.ExecutablePath);
            options.ReferencedAssemblies.AddRange(refs.ToArray());

            System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler();
            System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromFileBatch(options, files);

            foreach (System.CodeDom.Compiler.CompilerError err in results.Errors) {
                errors.Add(err);
            }

            if (results.Errors.Count == 0) {
                return results.CompiledAssembly;
            } else {
                return null;
            }
        }
        /// <summary>
        /// Generates an Assembly from a script filename
        /// </summary>
        /// <param name="filename">The filename of the script</param>
        /// <param name="references">Assembly references for the script</param>
        /// <returns>The generated assembly</returns>
        public Assembly CreateAssembly(string filename, IList references)
        {
            // ensure that compilerErrors is null
            compilerErrors = null;

            string extension = Path.GetExtension(filename);

            // Select the correct CodeDomProvider based on script file extension
            CodeDomProvider codeProvider = null;

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

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

            /*
             *              case ".js":
             *                      codeProvider = new Microsoft.JScript.JScriptCodeProvider();
             *                      break;
             */
            default:
                throw new InvalidOperationException("Script files must have a .cs, .vb, or .js extension, for C#, Visual Basic.NET, or JScript respectively.");
            }

            ICodeCompiler compiler = codeProvider.CreateCompiler();             //TODO: Update this

            // Set compiler parameters
            CompilerParameters compilerParams = new CompilerParameters();

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

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

            // Add custom references
            foreach (string reference in references)
            {
                if (!compilerParams.ReferencedAssemblies.Contains(reference))
                {
                    compilerParams.ReferencedAssemblies.Add(reference);
                }
            }

            // Do the compilation
            CompilerResults results = compiler.CompileAssemblyFromFile(compilerParams,
                                                                       filename);

            //Do we have any compiler errors
            if (results.Errors.Count > 0)
            {
                compilerErrors = results.Errors;
                throw new Exception(
                          "Compiler error(s) encountered and saved to AssemblyFactory.CompilerErrors");
            }

            Assembly createdAssembly = results.CompiledAssembly;

            return(createdAssembly);
        }
Пример #26
0
 void init_compiler()
 {
     Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider(); //!!VBSubst   Dim vb As New Microsoft.VisualBasic.VBCodeProvider()
     compiler = csharp.CreateCompiler();                                                     //!!VBSubst  compiler = vb.CreateCompiler()
 }
Пример #27
0
		CompilerResults Compile(MigrationContext context, CodeCompileUnit dom)
		{
			CompilerParameters parameters = new CompilerParameters();
			parameters.GenerateInMemory = true;
			parameters.ReferencedAssemblies.Add(GetType().Assembly.Location);
			parameters.ReferencedAssemblies.Add(context.TargetAssembly.Location);
			
			if (_references.Length > 0)
			{
				foreach (string reference in _references.Split(';'))
				{
					string assemblyName = reference.Trim();
					parameters.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);
				}
			}
			
			CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
			ICodeCompiler compiler = provider.CreateCompiler();
			return compiler.CompileAssemblyFromDom(parameters, dom);
		}
Пример #28
0
        public static ProjectReference GenerateWebProxyDLL(Project project, ServiceDescription desc)
        {
            ProjectReference refInfo = null;

            string nmspace = GetNamespaceFromUri(desc.RetrievalUrl);

            StringBuilder savedir = new StringBuilder();
            savedir.Append(project.BaseDirectory);
            savedir.Append(Path.DirectorySeparatorChar);
            savedir.Append("WebReferences");
            // second, create the path if it doesn't exist
            if(!Directory.Exists(savedir.ToString()))
                Directory.CreateDirectory(savedir.ToString());

            // generate the assembly
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            importer.AddServiceDescription(desc, null, null);

            CodeNamespace codeNamespace = new CodeNamespace(nmspace);
            CodeCompileUnit codeUnit = new CodeCompileUnit();
            codeUnit.Namespaces.Add(codeNamespace);
            importer.Import(codeNamespace, codeUnit);

            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler compiler;

            if(provider != null) {
                compiler = provider.CreateCompiler();
                CompilerParameters parms = new CompilerParameters();
                parms.ReferencedAssemblies.Add("System.Dll");
                parms.ReferencedAssemblies.Add("System.Xml.Dll");
                parms.ReferencedAssemblies.Add("System.Web.Services.Dll");
                parms.OutputAssembly = project.BaseDirectory + Path.DirectorySeparatorChar + "WebReferences" + Path.DirectorySeparatorChar + nmspace + ".Reference.Dll";
                CompilerResults results = compiler.CompileAssemblyFromDom(parms, codeUnit);
                Assembly assembly = results.CompiledAssembly;

                if(assembly != null) {
                    refInfo = new ProjectReference();
                    refInfo.ReferenceType = ReferenceType.Assembly;
                    refInfo.Reference = parms.OutputAssembly;
                }
            }

            return refInfo;
        }
Пример #29
0
        public void DoServiceEvent(int k2_workflowId, SerializableDictionary <string, string> dataFields)
        {
            StringBuilder txt = new StringBuilder();

            foreach (KeyValuePair <string, string> item in dataFields)
            {
                txt.AppendFormat("{0}|{1}$", item.Key, item.Value);
            }

            string param = txt.ToString().Trim('$');

            //1. 创建WebClient下载WSDL信息
            WebClient web    = new WebClient();
            Stream    stream = web.OpenRead(string.Format("{0}?wsdl", Url));

            // 2. 创建和格式化 WSDL 文档。
            ServiceDescription description = ServiceDescription.Read(stream);

            // 3. 创建客户端代理代理类。
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName = "Soap";                               // 指定访问协议。
            importer.Style        = ServiceDescriptionImportStyle.Client; // 生成客户端代理。

            importer.AddServiceDescription(description, null, null);      // 添加 WSDL 文档。

            // 4. 使用 CodeDom 编译客户端代理类。
            CodeNamespace   nmspace = new CodeNamespace(); // 为代理类添加命名空间,缺省为全局空间。
            CodeCompileUnit unit    = new CodeCompileUnit();

            unit.Namespaces.Add(nmspace);

            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);

            //5. 修改WebService接口的基类(默认基类是SoapHttpClientProtocol),而因为使用的wse2.0,所以需要修改基类以便后面传递身份验证信息
            //CodeTypeDeclaration ctDecl = nmspace.Types[0];
            //nmspace.Types.Remove(ctDecl);
            //ctDecl.BaseTypes[0] = new CodeTypeReference("Microsoft.Web.Services2.WebServicesClientProtocol");
            //nmspace.Types.Add(ctDecl);

            //创建代码生成器
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            //6. 指定代码生成器,并获得源码
            ICodeGenerator icg = provider.CreateGenerator();
            StringBuilder  srcStringBuilder = new StringBuilder();
            StringWriter   sw = new StringWriter(srcStringBuilder);

            icg.GenerateCodeFromNamespace(nmspace, sw, null);
            string proxySource = srcStringBuilder.ToString();

            sw.Close();

            //7. 创建编译的参数
            CompilerParameters parameter = new CompilerParameters();

            //注意以下两个属性设置为false才能在多次动态调用时不会报错
            parameter.GenerateExecutable = false;
            parameter.GenerateInMemory   = false;
            //用于输出dll文件,调试的时候查看结果
            //parameter.OutputAssembly = "WebService.dll"; // 可以指定你所需的任何文件名。
            parameter.ReferencedAssemblies.Add("System.dll");
            parameter.ReferencedAssemblies.Add("System.XML.dll");
            parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
            parameter.ReferencedAssemblies.Add("System.Data.dll");


            //8. 动态编译文件
            ICodeCompiler   compiler = provider.CreateCompiler();
            CompilerResults result   = compiler.CompileAssemblyFromSource(parameter, proxySource);//compiler.CompileAssemblyFromDom(parameter, unit);

            try
            {
                // 9. 检查编译是否出错
                if (!result.Errors.HasErrors)
                {
                    //10. 使用 Reflection 调用 WebService。
                    Assembly asm = result.CompiledAssembly;
                    // 如果在前面为代理类添加了命名空间,此处需要将命名空间添加到类型前面。

                    //foreach (var item in asm.GetTypes())
                    //{
                    //if (item.IsSubclassOf(typeof(FinallyDisposeServiceBase)))
                    //{
                    string className = WF_GetRelatedLinks.GetRelatedClassName(k2_workflowId.ToString());
                    Type   t         = asm.GetType(className);
                    object o         = Activator.CreateInstance(t);
                    //调用WebService的方法
                    MethodInfo method = t.GetMethod("InvokeService");
                    //传递方法所需参数
                    method.Invoke(o, new object[] { k2_workflowId, param });
                    //获取返回结果;
                    //    }
                    //}
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }
        }
Пример #30
0
        private string Execute(ITemplateGeneratorHost host, string relativePath, string templateFile, string outFileName)
        {
            Type compiledType = null;

            if (!_compiledAssemblies.Contains(templateFile))
            {
                string guid = Guid.NewGuid().ToString("N");
                string generatorClassName = "Template" + guid;
                string import             = @"using System;
using System.Collections;
";

                foreach (DictionaryEntry entry in _currentTemplateContext.Imports)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    import += "using " + tagAttributes["Namespace"].ToString() + ";\r\n";
                }

                string prefix = @"
namespace FluorineFx.CodeGenerator
{
	public class "     + generatorClassName + @" : Template
	{
		public "         + generatorClassName + @"(TemplateEngine templateEngine, ITemplateGeneratorHost host, TemplateContext templateContext) : base(templateEngine, host, templateContext)
		{
		}

		public void RunTemplate()
		{"        ;

                string suffix = @"
		}
	}
}";

                string code = import + prefix + _codeBuilder.ToString() + suffix;

                if (_templateEngineSettings.Trace)
                {
                    host.AddFile(relativePath, outFileName + ".trace.cs", code);
                }

                CodeDomProvider provider = null;
                //Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                //Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider();
                provider = new Microsoft.CSharp.CSharpCodeProvider();
#if (NET_1_1)
                ICodeCompiler compiler = provider.CreateCompiler();
#endif
                CompilerParameters options = new CompilerParameters();
                options.GenerateInMemory   = true;
                options.GenerateExecutable = false;
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    //options.ReferencedAssemblies.Add(Path.GetFileName(assembly.Location));
                    options.ReferencedAssemblies.Add(assembly.Location);
                }

                Uri    uri     = new Uri(Assembly.GetExecutingAssembly().CodeBase);
                string libPath = Path.GetDirectoryName(uri.LocalPath);
                options.CompilerOptions = "/lib:\"" + libPath + "\"";
                if (AppDomain.CurrentDomain.BaseDirectory != null)
                {
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\"";
                }
                if (AppDomain.CurrentDomain.DynamicDirectory != null)
                {
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.DynamicDirectory) + "\"";
                }

                foreach (DictionaryEntry entry in _currentTemplateContext.Assemblies)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    bool          referenced    = false;
                    foreach (string referencedAssembly in options.ReferencedAssemblies)
                    {
                        string assembly = Path.GetFileName(referencedAssembly);
                        if (assembly.ToLower() == tagAttributes["Name"].ToString().ToLower())
                        {
                            referenced = true;
                            break;
                        }
                    }
                    if (!referenced)
                    {
                        options.ReferencedAssemblies.Add(tagAttributes["Name"].ToString());
                    }
                }

                //log.Debug("Compiling code");
                //log.Debug(code);

                /*
                 * string output = Path.Combine(Path.GetTempPath(), generatorClassName + ".cs");
                 * using (StreamWriter sw = File.CreateText(output))
                 * {
                 *  sw.Write(code);
                 * }
                 */

#if (NET_1_1)
                CompilerResults results = compiler.CompileAssemblyFromSource(options, code);
#else
                CompilerResults results = provider.CompileAssemblyFromSource(options, code);
                //CompilerResults results = provider.CompileAssemblyFromFile(options, output);
#endif
                if (results.Errors.Count != 0)
                {
                    StringBuilder errorBuilder = new StringBuilder();
                    errorBuilder.Append("*** Compilation Errors ***\n");
                    log.Error("*** Compilation Errors ***");
                    foreach (CompilerError error in results.Errors)
                    {
                        errorBuilder.Append(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": ");
                        errorBuilder.Append(error.ErrorText);
                        errorBuilder.Append("\r\n");
                        log.Error(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": " + error.ErrorText);
                    }
                    host.AddFile(relativePath, outFileName + ".error.txt", errorBuilder.ToString());
                    return(errorBuilder.ToString());
                }

                compiledType = results.CompiledAssembly.GetType("FluorineFx.CodeGenerator." + generatorClassName);
                _compiledAssemblies[templateFile] = compiledType;
            }
            else
            {
                compiledType = _compiledAssemblies[templateFile] as Type;
            }

            TextWriter   saved  = Console.Out;
            StringWriter writer = new StringWriter();
            Console.SetOut(writer);
            try
            {
                object     generator = Activator.CreateInstance(compiledType, new object[] { this, host, _currentTemplateContext });//Assembly.CreateInstance("FluorineFx.CodeGenerator." + generatorClassName, true, BindingFlags.Public | BindingFlags.Instance, null, new object[] { this, host, _currentTemplateContext }, null, null);
                MethodInfo mi        = generator.GetType().GetMethod("RunTemplate");
                mi.Invoke(generator, new object[] {});
                return(writer.ToString());
            }
            catch (Exception ex)
            {
                log.Error("Error calling code generator", ex);
                Console.SetOut(saved);
                //Console.WriteLine(code.ToString());
                Console.WriteLine();
                Console.WriteLine("Unable to invoke entry point: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException);
                }
                return(ex.ToString());
            }
            finally
            {
                Console.SetOut(saved);
            }
        }
Пример #31
0
        private void SaveAssembly(string Path)
        {
            //Create a new object of the global CodeCompileUnit class.
            myassembly = new CodeCompileUnit();
            //Add the namespace to the assembly.
            myassembly.Namespaces.Add(mynamespace);
            //Add the following compiler parameters. (The references to the //standard .net dll(s) and framework library).
            CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll" });
            comparam.ReferencedAssemblies.Add("System.dll");
            comparam.ReferencedAssemblies.Add("System.Core.dll");
            comparam.ReferencedAssemblies.Add("System.Data.dll");
            comparam.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
            comparam.ReferencedAssemblies.Add("System.Xml.dll");
            comparam.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            comparam.ReferencedAssemblies.Add("System.Core.dll");
            //comparam.ReferencedAssemblies.Add("System.Collections.Generic.dll");
            comparam.ReferencedAssemblies.Add("Driver.dll");
            comparam.ReferencedAssemblies.Add("SupportLibrary.dll");
            comparam.ReferencedAssemblies.Add("log4net.dll");
            //Indicates Whether the compiler has to generate the output in //memory
            comparam.GenerateInMemory = false;
            //Indicates whether the output is an executable.
            comparam.GenerateExecutable = true;
            //provide the name of the class which contains the Main Entry //point method
            comparam.MainClass = "mynamespace.myclass";
            //provide the path where the generated assembly would be placed
            comparam.OutputAssembly = @Path;
            //Create an instance of the c# compiler and pass the assembly to //compile
            Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();

            //Build to cs file

            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            using (StreamWriter sourceWriter = new StreamWriter( @"release.cs"))
            {
                ccp.GenerateCodeFromCompileUnit(
                myassembly, sourceWriter, options);
            }

            ICodeCompiler icc = ccp.CreateCompiler();
            ////The CompileAssemblyFromDom would either return the list of
            ////compile time errors (if any), or would create the
            ////assembly in the respective path in case of successful //compilation
            CompilerResults compres = icc.CompileAssemblyFromDom(comparam, myassembly);
            if (compres == null || compres.Errors.Count > 0)
            {
                for (int i = 0; i < compres.Errors.Count; i++)
                {
                    //Console.WriteLine(compres.Errors[i]);
                    MessageShow.Writelog("CCodeGenerator.cs::", compres.Errors[i].ToString());
                }
            }
        }
Пример #32
0
        public FactoryIF getFactory(int level)
        {
            if (level.Equals(1))
            {
                return(new LevelOneFactory());
            }
            else if (level.Equals(2))
            {
                return(new LevelTwoFactory());
            }
            else if (level.Equals(3))
            {
                return(new LevelThreeFactory());
            }
            else if (level.Equals(4))
            {
                return(new LevelFourFactory());
            }
            else if (level.Equals(5))
            {
                return(new LevelFiveFactory());
            }
            else
            {
                try
                {
                    LevelPlayer player = LevelPlayer.getInstance();
                    string      dlevel = player.getFile();
                    String      code;
                    String      line;
                    //Pass the file path and file name to the StreamReader constructor

                    StreamReader sr = new StreamReader(dlevel);

                    //Read the first line of text
                    line = sr.ReadLine();
                    code = line;
                    //Continue to read until you reach end of file
                    while (line != null)
                    {
                        //Read the next line
                        line = sr.ReadLine();
                        code = code + "\n" + line;
                    }

                    //close the file
                    sr.Close();

                    Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                    ICodeCompiler compiler = provider.CreateCompiler();
                    System.CodeDom.Compiler.CompilerParameters compilerparams = new CompilerParameters();
                    compilerparams.GenerateExecutable = false;
                    compilerparams.GenerateInMemory   = true;
                    compilerparams.ReferencedAssemblies.Add("System.dll");
                    compilerparams.ReferencedAssemblies.Add("System.Core.dll");
                    compilerparams.ReferencedAssemblies.Add(typeof(Program).Assembly.Location);
                    CompilerResults results  = compiler.CompileAssemblyFromSource(compilerparams, code);
                    Assembly        compiled = null;
                    if (results.Errors.HasErrors)
                    {
                        StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
                        foreach (CompilerError error in results.Errors)
                        {
                            errors.AppendFormat("Line {0},{1}\t: {2}\n",
                                                error.Line, error.Column, error.ErrorText);
                        }
                        throw new Exception(errors.ToString());
                    }
                    else
                    {
                        compiled = results.CompiledAssembly;
                    }
                    int last = dlevel.LastIndexOf('\\');
                    last += 1;
                    Type      type   = compiled.GetType("WordBlaster.AbstractFactory." + dlevel.Substring(last, (dlevel.Count() - last - 4)));
                    FactoryIF dynlvl = (FactoryIF)Activator.CreateInstance(type);
                    return(dynlvl);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Could not load file, starting normally...");
                    return(new LevelOneFactory()); //if we could not load it in just start normally
                }
            }
        }
Пример #33
0
		public static object UploadData(string url, string @namespace, string classname, 
			string methodname, object[] args, ArrayList al)
		{
			try
			{
				System.Net.WebClient wc = new System.Net.WebClient();
				//System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
				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, string.Empty, string.Empty); //将sd描述导入到sdi中
				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.ICodeCompiler icc = csc.CreateCompiler();

				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 = icc.CompileAssemblyFromDom(cplist, ccu);
				if (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);

				ParameterModifier[] paramsModifer = new ParameterModifier[1];
				paramsModifer[0] = new ParameterModifier(args.Length);
				//paramsModifer[0][7] = true;

				object result = t.InvokeMember(methodname, BindingFlags.Default | BindingFlags.InvokeMethod, null,
					obj, args, paramsModifer, null, null);

				//al.Add(args[7]);
				return result;
			}
			catch (Exception ex)
			{
				WriteLog(ex.Message, EXCEPTION_LOG_TITLE);
				return null;
			}
		}
Пример #34
0
        private Assembly GenerateExecutableAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare namespace, default is Prolog.Assembly
            CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");

            plNamespace.Imports.Add(new CodeNamespaceImport("System"));
            plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
            plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));

            compileUnit.Namespaces.Add(plNamespace);

            // Declare class type
            CodeTypeDeclaration classType = new CodeTypeDeclaration("PrologApp");
            plNamespace.Types.Add(classType);
            classType.TypeAttributes = TypeAttributes.Public;

            // Declare private members
            CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");

            CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");

            classType.Members.Add(machineField);
            classType.Members.Add(moreField);

            // Generate constructor method
            CodeConstructor cons = new CodeConstructor();
            cons.Attributes = MemberAttributes.Public;
            cons.Statements.Add(new CodeSnippetExpression("Init()"));
            classType.Members.Add(cons);

            // Generate Init() method
            GenerateInitMethod(classType, instructions);

            // Generate main method
            CodeEntryPointMethod mainMethod = new CodeEntryPointMethod();
            mainMethod.Name = "Main";
            mainMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            mainMethod.Statements.Add(new CodeSnippetStatement("PrologApp app = new PrologApp();"));
            mainMethod.Statements.Add(new CodeSnippetStatement("app.Run();"));
            classType.Members.Add(mainMethod);

            CodeMemberMethod runMethod = new CodeMemberMethod();
            runMethod.Name = "Run";
            runMethod.Attributes = MemberAttributes.Public;
            runMethod.Statements.Add(new CodeSnippetStatement("machine.Call(\"main\");"));
            classType.Members.Add(runMethod);

            // Compile the file into a DLL
            CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });

            compparams.GenerateInMemory = false;
            compparams.GenerateExecutable = true;
            compparams.OutputAssembly = compilerParameters.OutputAssembly;
            compparams.TempFiles.KeepFiles = true;

            Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler cscompiler = csharp.CreateCompiler();

            CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);

            if (compresult.Errors.Count > 0)
            {
                foreach (CompilerError err in compresult.Errors)
                {
                    Console.WriteLine(err);
                }
                return null;
            }

            return compresult.CompiledAssembly;
        }
Пример #35
0
        /// <summary>
        /// Generates an Assembly from a list of script filenames
        /// </summary>
        /// <param name="filenames">The filenames of the scripts</param>
        /// <param name="references">Assembly references for the script</param>
        /// <returns>The generated assembly</returns>
        public Assembly CreateAssembly(IList filenames, IList references)
        {
            string fileType = null;

            foreach (string filename in filenames)
            {
                string extension = Path.GetExtension(filename);
                if (fileType == null)
                {
                    fileType = extension;
                }
                else if (fileType != extension)
                {
                    throw new ArgumentException("All files in the file list must be of the same type.");
                }
            }

            // ensure that compilerErrors is null
            compilerErrors = null;

            // Select the correct CodeDomProvider based on script file extension
            CodeDomProvider codeProvider = null;

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

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

            case ".js":
                //   codeProvider = new Microsoft.JScript.JScriptCodeProvider();
                break;

            default:
                throw new InvalidOperationException("Script files must have a .cs, .vb, or .js extension, for C#, Visual Basic.NET, or JScript respectively.");
            }

            ICodeCompiler compiler = codeProvider.CreateCompiler();

            // Set compiler parameters
            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");

            // Add custom references
            foreach (string reference in references)
            {
                if (!compilerParams.ReferencedAssemblies.Contains(reference))
                {
                    compilerParams.ReferencedAssemblies.Add(reference);
                }
            }

            // Do the compilation
            CompilerResults results = compiler.CompileAssemblyFromFileBatch(
                compilerParams, (string[])ArrayList.Adapter(filenames).ToArray(typeof(string)));

            // Do we have any compiler errors
            if (results.Errors.Count > 0)
            {
                compilerErrors = results.Errors;
                throw new Exception(
                          "Compiler error(s) encountered and saved to AssemblyFactory.CompilerErrors");
            }

            Assembly createdAssembly = results.CompiledAssembly;

            return(createdAssembly);
        }
Пример #36
0
		protected void PreCompile()
		{
			#if !COMPACT
			CodeDomProvider theProvider;
			switch(Type)
			{
				case "CSharp":
				case "C#":
				case "csharp":
				case "C Sharp":
				case "C sharp":
					theProvider = new Microsoft.CSharp.CSharpCodeProvider();
					break;
					//   case "JScript":
					//     theProvider = new Microsoft.JScript.JScriptCodeProvider();
					//     break;
				case "Visual Basic":
				case "VB":
				case "VB.Net":
				case "vb":
				case "vb.net":
				case "VB.NET":
					theProvider = new Microsoft.VisualBasic.VBCodeProvider();
					break;
				default:
					theProvider = new Microsoft.CSharp.CSharpCodeProvider();
					break;
			}
			ICodeCompiler theCompiler = theProvider.CreateCompiler();
			CompilerParameters compParams = new CompilerParameters();
			IEnumerator enumLibs = ExternalLibraries.Instance.LoadedAssemblies;
			while(enumLibs.MoveNext())
				compParams.ReferencedAssemblies.Add(((Assembly)enumLibs.Current).GetName().Name);
			compParams.GenerateExecutable = true;
			compParams.GenerateInMemory = true;
			CompilerResults crs = theCompiler.CompileAssemblyFromSource(compParams, ScriptSource);
			if(crs.Errors.HasErrors)
				for(int i=0; i< crs.Errors.Count; i++)
					Console.WriteLine(crs.Errors[i]);
			m_compiledAssemly = crs.CompiledAssembly;
			//if fails: wrap source in main method + class -> recompile
			#endif
		}
Пример #37
0
        private static void DoBenchmark(XmlTextWriter xtw, IBenchmark b)
        {
            Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            Console.WriteLine("Benchmark: {0}", b.Name);

            if (File.Exists("BenchmarkAssembly." + b.Name + ".dll"))
            {
                File.Delete("BenchmarkAssembly." + b.Name + ".dll");
            }

            CompilerParameters options = new CompilerParameters();

            options.OutputAssembly     = "BenchmarkAssembly." + b.Name + ".dll";
            options.GenerateInMemory   = true;
            options.GenerateExecutable = false;
            foreach (string s in b.References)
            {
                options.ReferencedAssemblies.Add(s);
            }
            options.CompilerOptions = "/optimize+";
            //options.IncludeDebugInformation = true;

            string sourceCode = GenerateTestSourceCode(b);

            using (StreamWriter sw = File.CreateText("BenchmarkAssembly." + b.Name + ".cs"))
            {
                sw.Write(sourceCode);
            }

            CompilerResults results = provider.CreateCompiler().CompileAssemblyFromSource(options, sourceCode);

            foreach (CompilerError ce in results.Errors)
            {
                Console.WriteLine("ERROR in line {0}: {1}", ce.Line, ce.ErrorText);
            }
            if (results.Errors.Count > 0)
            {
                Console.WriteLine("Errors in generated code for " + b.Name + " Ignoring.");
                return;
            }

            //Console.WriteLine("Compiled to assembly: {0}", results.CompiledAssembly.FullName);
            xtw.WriteStartElement("framework");
            xtw.WriteAttributeString("name", b.Name);

            Type t = results.CompiledAssembly.GetType("TheBenchmark");

            double min, max, avg;

            TimeAndDiscardUnusual(null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "DoNothing"), null, 100000, 10, out min, out max, out avg);
            _overhead = min;

            Console.WriteLine("overhead: {0}", _overhead);

            RunDelegate init  = (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "Init");
            RunDelegate flush = (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "Flush");

            init();

            TimeAndDisplay("Guarded no logging", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "GuardedNoLogging"), null, 100000, 5);
            TimeAndDisplay("Unguarded no logging", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLogging"), null, 100000, 5);
            TimeAndDisplay("Unguarded no logging with formatting 1", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting1"), null, 10000, 5);
            TimeAndDisplay("Unguarded no logging with formatting 2", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting2"), null, 10000, 5);
            TimeAndDisplay("Unguarded no logging with formatting 3", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting3"), null, 10000, 5);
            TimeAndDisplay("Null target without rendering", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithoutFormatting"), flush, 10000, 5);
            TimeAndDisplay("Null target without rendering 1", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithFormatting1"), flush, 10000, 5);
            TimeAndDisplay("Null target without rendering 3", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithFormatting3"), flush, 10000, 5);
            TimeAndDisplay("Null target with rendering", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithoutFormatting"), flush, 1000, 5);
            TimeAndDisplay("Null target with rendering 1", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithFormatting1"), flush, 1000, 5);
            TimeAndDisplay("Null target with rendering 3", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithFormatting3"), flush, 1000, 5);
            TimeAndDisplay("Simple file", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "SimpleFile"), flush, 10, 5);
            //TimeAndDisplay("Buffered file", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "BufferedFile"), flush, 100, 5);
            //TimeAndDisplay("Asynchronous File without a flush", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "AsyncFile"), null, 100, 5);
            //flush();
            //TimeAndDisplay("Asynchronous File with a flush", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "AsyncFile"), flush, 5000, 5);

            xtw.WriteEndElement();
        }
Пример #38
0
        public static object InvokeWebservice(string url, string nsClassName, string methodname, int timeout, params object[] args)
        {
            if (args.Length == 1 && args[0] is ArrayList)
            {
                args = (args[0] as ArrayList).ToArray();
            }
            try
            {
                int    li         = nsClassName.LastIndexOf('.');
                string @namespace = (li == -1 ? "" : nsClassName.Substring(0, li));

                Assembly assembly;
                if (_assenblyCache == null)
                {
                    _assenblyCache = new Hashtable();
                }
                if (_assenblyCache.ContainsKey(url.ToUpper()))
                {
                    assembly = (Assembly)_assenblyCache[url.ToUpper()];
                }
                else
                {
                    System.Net.WebClient wc     = new System.Net.WebClient();
                    System.IO.Stream     stream = wc.OpenRead(url + "?WSDL");
                    //Configuration.SoapEnvelopeProcessingElement se = new Configuration.SoapEnvelopeProcessingElement();
                    //se.ReadTimeout = 15000;

                    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);

                    Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.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 (CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(System.Environment.NewLine);
                        }
                        throw new Exception(sb.ToString());
                    }
                    assembly = cr.CompiledAssembly;
                    _assenblyCache[url.ToUpper()] = assembly;
                }
                Type t = null;
                if (String.IsNullOrEmpty(nsClassName))
                {
                    t = assembly.GetTypes()[0];
                }
                else
                {
                    t = assembly.GetType(nsClassName, true, true);
                }
                MethodInfo mi = null;
                if (String.IsNullOrEmpty(methodname))
                {
                    mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)[0];
                }
                else
                {
                    mi = t.GetMethod(methodname);
                }
                SoapHttpClientProtocol obj = Activator.CreateInstance(t) as SoapHttpClientProtocol;
                SetCookie(url, obj);
                //obj.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                obj.Timeout = timeout;
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Пример #39
0
		private string Execute(ITemplateGeneratorHost host, string relativePath, string templateFile, string outFileName)
		{
            Type compiledType = null;
            if (!_compiledAssemblies.Contains(templateFile))
            {
                string guid = Guid.NewGuid().ToString("N");
                string generatorClassName = "Template" + guid;
                string import = @"using System;
using System.Collections;
";

                foreach (DictionaryEntry entry in _currentTemplateContext.Imports)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    import += "using " + tagAttributes["Namespace"].ToString() + ";\r\n";
                }

                string prefix = @"
namespace FluorineFx.CodeGenerator
{
	public class " + generatorClassName + @" : Template
	{
		public " + generatorClassName + @"(TemplateEngine templateEngine, ITemplateGeneratorHost host, TemplateContext templateContext) : base(templateEngine, host, templateContext)
		{
		}

		public void RunTemplate()
		{";

                string suffix = @"
		}
	}
}";

                string code = import + prefix + _codeBuilder.ToString() + suffix;

                if (_templateEngineSettings.Trace)
                {
                    host.AddFile(relativePath, outFileName + ".trace.cs", code);
                }

                CodeDomProvider provider = null;
                //Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                //Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider();
                provider = new Microsoft.CSharp.CSharpCodeProvider();
#if (NET_1_1)
			ICodeCompiler compiler = provider.CreateCompiler();
#endif
                CompilerParameters options = new CompilerParameters();
                options.GenerateInMemory = true;
                options.GenerateExecutable = false;
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    //options.ReferencedAssemblies.Add(Path.GetFileName(assembly.Location));
                    options.ReferencedAssemblies.Add(assembly.Location);
                }

                Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
                string libPath = Path.GetDirectoryName(uri.LocalPath);
                options.CompilerOptions = "/lib:\"" + libPath + "\"";
                if (AppDomain.CurrentDomain.BaseDirectory != null)
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\"";
                if (AppDomain.CurrentDomain.DynamicDirectory != null)
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.DynamicDirectory) + "\"";

                foreach (DictionaryEntry entry in _currentTemplateContext.Assemblies)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    bool referenced = false;
                    foreach (string referencedAssembly in options.ReferencedAssemblies)
                    {
                        string assembly = Path.GetFileName(referencedAssembly);
                        if (assembly.ToLower() == tagAttributes["Name"].ToString().ToLower())
                        {
                            referenced = true;
                            break;
                        }
                    }
                    if (!referenced)
                        options.ReferencedAssemblies.Add(tagAttributes["Name"].ToString());
                }

                //log.Debug("Compiling code");
                //log.Debug(code);

                /*
                string output = Path.Combine(Path.GetTempPath(), generatorClassName + ".cs");
                using (StreamWriter sw = File.CreateText(output))
                {
                    sw.Write(code);
                }
                */

#if (NET_1_1)
			CompilerResults results = compiler.CompileAssemblyFromSource(options, code);
#else
                CompilerResults results = provider.CompileAssemblyFromSource(options, code);
                //CompilerResults results = provider.CompileAssemblyFromFile(options, output);
#endif
                if (results.Errors.Count != 0)
                {
                    StringBuilder errorBuilder = new StringBuilder();
                    errorBuilder.Append("*** Compilation Errors ***\n");
                    log.Error("*** Compilation Errors ***");
                    foreach (CompilerError error in results.Errors)
                    {
                        errorBuilder.Append(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": ");
                        errorBuilder.Append(error.ErrorText);
                        errorBuilder.Append("\r\n");
                        log.Error(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": " + error.ErrorText);
                    }
                    host.AddFile(relativePath, outFileName + ".error.txt", errorBuilder.ToString());
                    return errorBuilder.ToString();
                }

                compiledType = results.CompiledAssembly.GetType("FluorineFx.CodeGenerator." + generatorClassName);
                _compiledAssemblies[templateFile] = compiledType;
            }
            else
                compiledType = _compiledAssemblies[templateFile] as Type;

			TextWriter saved = Console.Out;
			StringWriter writer = new StringWriter();
			Console.SetOut(writer);
			try
			{
                object generator = Activator.CreateInstance(compiledType, new object[] { this, host, _currentTemplateContext });//Assembly.CreateInstance("FluorineFx.CodeGenerator." + generatorClassName, true, BindingFlags.Public | BindingFlags.Instance, null, new object[] { this, host, _currentTemplateContext }, null, null);
				MethodInfo mi = generator.GetType().GetMethod("RunTemplate");
				mi.Invoke(generator, new object[]{} );
				return writer.ToString();
			}
			catch (Exception ex)
			{
				log.Error("Error calling code generator", ex);
				Console.SetOut(saved);
				//Console.WriteLine(code.ToString());
				Console.WriteLine();
				Console.WriteLine("Unable to invoke entry point: {0}", ex.Message);
				if (ex.InnerException != null)
					Console.WriteLine(ex.InnerException);
				return ex.ToString();
			}
			finally
			{
				Console.SetOut(saved);
			}
		}
Пример #40
0
        private static void DoBenchmark(XmlTextWriter xtw, IBenchmark b)
        {
            Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            Console.WriteLine("Benchmark: {0}", b.Name);

            if (File.Exists("BenchmarkAssembly." + b.Name + ".dll"))
                File.Delete("BenchmarkAssembly." + b.Name + ".dll");

            CompilerParameters options = new CompilerParameters();
            options.OutputAssembly = "BenchmarkAssembly." + b.Name + ".dll";
            options.GenerateInMemory = true;
            options.GenerateExecutable = false;
            foreach (string s in b.References)
                options.ReferencedAssemblies.Add(s);
            options.CompilerOptions = "/optimize+";
            //options.IncludeDebugInformation = true;

            string sourceCode = GenerateTestSourceCode(b);
            
            using (StreamWriter sw = File.CreateText("BenchmarkAssembly." + b.Name + ".cs"))
            {
                sw.Write(sourceCode);
            }

            CompilerResults results = provider.CreateCompiler().CompileAssemblyFromSource(options, sourceCode);
            foreach (CompilerError ce in results.Errors)
            {
                Console.WriteLine("ERROR in line {0}: {1}", ce.Line, ce.ErrorText);
            }
            if (results.Errors.Count > 0)
            {
                Console.WriteLine("Errors in generated code for " + b.Name + " Ignoring.");
                return;
            }

            //Console.WriteLine("Compiled to assembly: {0}", results.CompiledAssembly.FullName);
            xtw.WriteStartElement("framework");
            xtw.WriteAttributeString("name", b.Name);

            Type t = results.CompiledAssembly.GetType("TheBenchmark");

            double min, max, avg;

            TimeAndDiscardUnusual(null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "DoNothing"), null, 100000, 10, out min, out max, out avg);
            _overhead = min;

            Console.WriteLine("overhead: {0}", _overhead);

            RunDelegate init = (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "Init");
            RunDelegate flush = (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "Flush");

            init();

            TimeAndDisplay("Guarded no logging", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "GuardedNoLogging"), null, 100000, 5);
            TimeAndDisplay("Unguarded no logging", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLogging"), null, 100000, 5);
            TimeAndDisplay("Unguarded no logging with formatting 1", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting1"), null, 10000, 5);
            TimeAndDisplay("Unguarded no logging with formatting 2", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting2"), null, 10000, 5);
            TimeAndDisplay("Unguarded no logging with formatting 3", xtw, null, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoLoggingWithFormatting3"), null, 10000, 5);
            TimeAndDisplay("Null target without rendering", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithoutFormatting"), flush, 10000, 5);
            TimeAndDisplay("Null target without rendering 1", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithFormatting1"), flush, 10000, 5);
            TimeAndDisplay("Null target without rendering 3", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NoRenderingLoggingWithFormatting3"), flush, 10000, 5);
            TimeAndDisplay("Null target with rendering", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithoutFormatting"), flush, 1000, 5);
            TimeAndDisplay("Null target with rendering 1", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithFormatting1"), flush, 1000, 5);
            TimeAndDisplay("Null target with rendering 3", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "NullLoggingWithFormatting3"), flush, 1000, 5);
            TimeAndDisplay("Simple file", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "SimpleFile"), flush, 10, 5);
            //TimeAndDisplay("Buffered file", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "BufferedFile"), flush, 100, 5);
            //TimeAndDisplay("Asynchronous File without a flush", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "AsyncFile"), null, 100, 5);
            //flush();
            //TimeAndDisplay("Asynchronous File with a flush", xtw, init, (RunDelegate)Delegate.CreateDelegate(typeof(RunDelegate), t, "AsyncFile"), flush, 5000, 5);

            xtw.WriteEndElement();
        }
Пример #41
0
        private Assembly GenerateDllAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions, PrologCodeUnit unit)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare namespace, default is Prolog.Assembly
            CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");

            plNamespace.Imports.Add(new CodeNamespaceImport("System"));
            plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
            plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));

            compileUnit.Namespaces.Add(plNamespace);

            // Declare class type
            CodeTypeDeclaration classType = new CodeTypeDeclaration(unit.Class);

            plNamespace.Types.Add(classType);
            classType.TypeAttributes = TypeAttributes.Public;

            // Declare private members
            CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");
            CodeMemberField moreField    = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");

            classType.Members.Add(machineField);
            classType.Members.Add(moreField);

            // Generate constructor method
            CodeConstructor cons = new CodeConstructor();

            cons.Attributes = MemberAttributes.Public;
            cons.Statements.Add(new CodeSnippetExpression("Init()"));
            classType.Members.Add(cons);

            // Generate the 'More' property
            CodeMemberProperty moreProperty = new CodeMemberProperty();

            moreProperty.Attributes = MemberAttributes.Public;
            moreProperty.Name       = "More";
            moreProperty.HasGet     = true;
            moreProperty.HasSet     = false;
            moreProperty.Type       = new CodeTypeReference("System.Boolean");
            string getStmt1 = "if (machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\")) {  _more = false; } ";
            string getStmt2 = "return !(machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\"));";

            moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt1));
            moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt2));
            classType.Members.Add(moreProperty);

            // Generate Redo() method
            CodeMemberMethod redoMethod = new CodeMemberMethod();

            redoMethod.Name = "Redo";
            redoMethod.Statements.Add(new CodeSnippetStatement("machine.Backtrack();"));
            redoMethod.Statements.Add(new CodeSnippetStatement("_more = true;"));
            redoMethod.Attributes = MemberAttributes.Public;
            classType.Members.Add(redoMethod);

            // Generate Init() method
            GenerateInitMethod(classType, instructions);

            // Generate method signatures
            GenerateMethodSignatures(classType, instructions);

            // Compile the file into a DLL
            CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });

            compparams.GenerateInMemory    = false;
            compparams.OutputAssembly      = compilerParameters.OutputAssembly;
            compparams.TempFiles.KeepFiles = true;


            Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler cscompiler = csharp.CreateCompiler();

            CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);

            if (compresult.Errors.Count > 0)
            {
                foreach (CompilerError err in compresult.Errors)
                {
                    Console.WriteLine(err);
                }
                return(null);
            }

            return(compresult.CompiledAssembly);
        }
Пример #42
0
        private Assembly GenerateDllAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions, PrologCodeUnit unit)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare namespace, default is Prolog.Assembly
            CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");

            plNamespace.Imports.Add(new CodeNamespaceImport("System"));
            plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
            plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));

            compileUnit.Namespaces.Add(plNamespace);

            // Declare class type
            CodeTypeDeclaration classType = new CodeTypeDeclaration(unit.Class);
            plNamespace.Types.Add(classType);
            classType.TypeAttributes = TypeAttributes.Public;

            // Declare private members
            CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");
            CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");

            classType.Members.Add(machineField);
            classType.Members.Add(moreField);

            // Generate constructor method
            CodeConstructor cons = new CodeConstructor();
            cons.Attributes = MemberAttributes.Public;
            cons.Statements.Add(new CodeSnippetExpression("Init()"));
            classType.Members.Add(cons);

            // Generate the 'More' property
            CodeMemberProperty moreProperty = new CodeMemberProperty();
            moreProperty.Attributes = MemberAttributes.Public;
            moreProperty.Name = "More";
            moreProperty.HasGet = true;
            moreProperty.HasSet = false;
            moreProperty.Type = new CodeTypeReference("System.Boolean");
            string getStmt1 = "if (machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\")) {  _more = false; } ";
            string getStmt2 = "return !(machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\"));";
            moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt1));
            moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt2));
            classType.Members.Add(moreProperty);

            // Generate Redo() method
            CodeMemberMethod redoMethod = new CodeMemberMethod();
            redoMethod.Name = "Redo";
            redoMethod.Statements.Add(new CodeSnippetStatement("machine.Backtrack();"));
            redoMethod.Statements.Add(new CodeSnippetStatement("_more = true;"));
            redoMethod.Attributes = MemberAttributes.Public;
            classType.Members.Add(redoMethod);

            // Generate Init() method
            GenerateInitMethod(classType, instructions);

            // Generate method signatures
            GenerateMethodSignatures(classType, instructions);

            // Compile the file into a DLL
            CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });

            compparams.GenerateInMemory = false;
            compparams.OutputAssembly = compilerParameters.OutputAssembly;
            compparams.TempFiles.KeepFiles = true;

            Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler cscompiler = csharp.CreateCompiler();

            CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);

            if (compresult.Errors.Count > 0)
            {
                foreach(CompilerError err in compresult.Errors)
                {
                    Console.WriteLine(err);
                }
                return null;
            }

            return compresult.CompiledAssembly;
        }
Пример #43
0
        internal Assembly Compile()
        {
            CodeDomProvider    codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler      compiler     = codeProvider.CreateCompiler();
            CompilerParameters options      = new CompilerParameters(Imports);

            // allows us to catch the "'X' is defined in multiple places" warning (1595)
            options.WarningLevel = 1;

            if (CompModSwitches.KeepTempFiles.Enabled)
            {
                options.GenerateInMemory        = false;
                options.IncludeDebugInformation = true;
                options.TempFiles           = new TempFileCollection();
                options.TempFiles.KeepFiles = true;
            }
            else
            {
                options.GenerateInMemory = true;
            }

            // CONSIDER, stefanph: we should probably have a specific CodeDomPermission.
            PermissionSet perms = new PermissionSet(PermissionState.None);

            perms.AddPermission(FileIOPermission);
            perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            perms.Assert();

            CompilerResults results  = null;
            Assembly        assembly = null;

            try {
                results  = compiler.CompileAssemblyFromSource(options, writer.ToString());
                assembly = results.CompiledAssembly;
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            // check the output for errors or a certain level-1 warning (1595)
            if (results.Errors.Count > 0)
            {
                StringWriter stringWriter = new StringWriter();
                stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString()));
                bool foundOne = false;
                foreach (CompilerError e in results.Errors)
                {
                    // clear filename. This makes ToString() print just error number and message.
                    e.FileName = "";
                    if (!e.IsWarning || e.ErrorNumber == "CS1595")
                    {
                        foundOne = true;
                        stringWriter.WriteLine(e.ToString());
                    }
                }
                if (foundOne)
                {
                    throw new InvalidOperationException(stringWriter.ToString());
                }
            }
            // somehow we got here without generating an assembly
            if (assembly == null)
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));
            }

            return(assembly);
        }
Пример #44
0
        internal Assembly Compile()
        {
            CodeDomProvider    codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler      compiler     = codeProvider.CreateCompiler();
            CompilerParameters options      = new CompilerParameters(Imports);

            options.WarningLevel          = 1;
            options.TreatWarningsAsErrors = true;
            options.CompilerOptions       = "/nowarn:183,184,602,612,626,672,679,1030,1200,1201,1202,1203,1522,1570,1574,1580,1581,1584,1589,1590,1592,1596,1598,1607,2002,2014,2023,3012,5000";

            if (CompModSwitches.KeepTempFiles.Enabled)
            {
                options.GenerateInMemory        = false;
                options.IncludeDebugInformation = true;
                options.TempFiles           = new TempFileCollection();
                options.TempFiles.KeepFiles = true;
            }
            else
            {
                options.GenerateInMemory = true;
            }

            PermissionSet perms = new PermissionSet(PermissionState.Unrestricted);

            perms.AddPermission(FileIOPermission);
            perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            perms.Assert();

            CompilerResults results  = null;
            Assembly        assembly = null;

            try {
                results  = compiler.CompileAssemblyFromSource(options, writer.ToString());
                assembly = results.CompiledAssembly;
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }


            if (results.Errors.HasErrors)
            {
                StringWriter stringWriter = new StringWriter();
                stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString()));
                foreach (CompilerError e in results.Errors)
                {
                    // clear filename. This makes ToString() print just error number and message.
                    e.FileName = "";
                    stringWriter.WriteLine(e.ToString());
                }
                System.Diagnostics.Debug.WriteLine(stringWriter.ToString());
                throw new InvalidOperationException(stringWriter.ToString());
            }

            // somehow we got here without generating an assembly
            if (assembly == null)
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));
            }

            return(assembly);
        }
Пример #45
0
            private static KeyValuePair <bool, object> RunCSharpCode(string CSharpCode, ulong currentGuild, ulong currentChannel, bool ShowErrors, string StringParameter)
            {
                try
                {
                    #region Encapsulate Code into a single Method
                    string Code =
                        "using System;" + Environment.NewLine +
                        "using System.IO;" + Environment.NewLine +
                        "using System.Text;" + Environment.NewLine +
                        "using System.Collections;" + Environment.NewLine +
                        "using System.Linq;" + Environment.NewLine +
                        "using System.Diagnostics;" + Environment.NewLine +
                        "using System.Xml;" + Environment.NewLine +
                        "using System.Reflection;" + Environment.NewLine +
                        "using System.Collections.Generic;" + Environment.NewLine +
                        "using System.Web;" + Environment.NewLine +
                        "using System.Threading.Tasks;" + Environment.NewLine +
                        "using Newtonsoft.Json;" + Environment.NewLine +
                        "using GafBot;" + Environment.NewLine +
                        "using GafBot.MessageSystem;" + Environment.NewLine +
                        "using GafBot.Osu;" + Environment.NewLine +
                        "using GafBot.Osu.Api;" + Environment.NewLine +

                        "public class UserClass" + Environment.NewLine +
                        "{" + Environment.NewLine +
                        "public object UserMethod( string StringParameter )" + Environment.NewLine +
                        "{" + Environment.NewLine +
                        "object Result = null;" + Environment.NewLine +
                        "var dclient = Coding.Methods.GetClient();" + Environment.NewLine +
                        Environment.NewLine +
                        Environment.NewLine +

                        CSharpCode +

                        Environment.NewLine +
                        Environment.NewLine +
                        "return Result;" + Environment.NewLine +
                        "}" + Environment.NewLine +
                        "}";
                    #endregion

                    #region Compile the Dll to Memory

                    #region Make Reference List
                    Assembly[] FullAssemblyList = AppDomain.CurrentDomain.GetAssemblies();

                    System.Collections.Specialized.StringCollection ReferencedAssemblies_sc = new System.Collections.Specialized.StringCollection();

                    foreach (Assembly ThisAssebly in FullAssemblyList)
                    {
                        try
                        {
                            if (ThisAssebly is System.Reflection.Emit.AssemblyBuilder)
                            {
                                // Skip dynamic assemblies
                                continue;
                            }

                            ReferencedAssemblies_sc.Add(ThisAssebly.Location);
                        }
                        catch (NotSupportedException)
                        {
                            // Skip other dynamic assemblies
                            continue;
                        }
                    }

                    string[] ReferencedAssemblies = new string[ReferencedAssemblies_sc.Count];
                    ReferencedAssemblies_sc.CopyTo(ReferencedAssemblies, 0);
                    #endregion

                    Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
#pragma warning disable CS0618 // Type or member is obsolete
                    System.CodeDom.Compiler.ICodeCompiler CSharpCompiler = codeProvider.CreateCompiler();
#pragma warning restore CS0618 // Type or member is obsolete
                    System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters(ReferencedAssemblies)
                    {
                        GenerateExecutable      = false,
                        GenerateInMemory        = true,
                        IncludeDebugInformation = false,
                        OutputAssembly          = "ScreenFunction"
                    };
                    System.CodeDom.Compiler.CompilerResults CompileResult = CSharpCompiler.CompileAssemblyFromSource(parameters, Code);
                    #endregion

                    if (CompileResult.Errors.HasErrors == false)
                    { // Successful Compile
                        #region Run "UserMethod" from "UserClass"
                        System.Type UserClass = CompileResult.CompiledAssembly.GetType("UserClass");
                        object      Instance  = Activator.CreateInstance(UserClass, false);
                        return(new KeyValuePair <bool, object>(true, UserClass.GetMethod("UserMethod").Invoke(Instance, new object[] { StringParameter })));

                        #endregion
                    }
                    else // Failed Compile
                    {
                        if (ShowErrors)
                        {
                            #region Show Errors
                            StringBuilder ErrorText = new StringBuilder();

                            foreach (System.CodeDom.Compiler.CompilerError Error in CompileResult.Errors)
                            {
                                ErrorText.Append("Line " + (Error.Line - 1) +
                                                 " (" + Error.ErrorText + ")" +
                                                 Environment.NewLine);
                            }

                            Logger.Log("Compiler: " + ErrorText.ToString(), LogLevel.Trace);
                            #endregion
                        }
                    }
                }
                catch (Exception E)
                {
                    if (ShowErrors)
                    {
                        return(new KeyValuePair <bool, object>(false, E));
                    }
                }

                return(new KeyValuePair <bool, object>(false, null));
            }
Пример #46
0
        private Assembly GenerateExecutableAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare namespace, default is Prolog.Assembly
            CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");

            plNamespace.Imports.Add(new CodeNamespaceImport("System"));
            plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
            plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));

            compileUnit.Namespaces.Add(plNamespace);

            // Declare class type
            CodeTypeDeclaration classType = new CodeTypeDeclaration("PrologApp");

            plNamespace.Types.Add(classType);
            classType.TypeAttributes = TypeAttributes.Public;

            // Declare private members
            CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");

            CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");

            classType.Members.Add(machineField);
            classType.Members.Add(moreField);

            // Generate constructor method
            CodeConstructor cons = new CodeConstructor();

            cons.Attributes = MemberAttributes.Public;
            cons.Statements.Add(new CodeSnippetExpression("Init()"));
            classType.Members.Add(cons);


            // Generate Init() method
            GenerateInitMethod(classType, instructions);

            // Generate main method
            CodeEntryPointMethod mainMethod = new CodeEntryPointMethod();

            mainMethod.Name       = "Main";
            mainMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            mainMethod.Statements.Add(new CodeSnippetStatement("PrologApp app = new PrologApp();"));
            mainMethod.Statements.Add(new CodeSnippetStatement("app.Run();"));
            classType.Members.Add(mainMethod);


            CodeMemberMethod runMethod = new CodeMemberMethod();

            runMethod.Name       = "Run";
            runMethod.Attributes = MemberAttributes.Public;
            runMethod.Statements.Add(new CodeSnippetStatement("machine.Call(\"main\");"));
            classType.Members.Add(runMethod);


            // Compile the file into a DLL
            CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });

            compparams.GenerateInMemory    = false;
            compparams.GenerateExecutable  = true;
            compparams.OutputAssembly      = compilerParameters.OutputAssembly;
            compparams.TempFiles.KeepFiles = true;

            Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
            ICodeCompiler cscompiler = csharp.CreateCompiler();

            CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);

            if (compresult.Errors.Count > 0)
            {
                foreach (CompilerError err in compresult.Errors)
                {
                    Console.WriteLine(err);
                }
                return(null);
            }

            return(compresult.CompiledAssembly);
        }
Пример #47
0
        private void initDimensional(string expression)
        {
            Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler();
            System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();

            cpar.GenerateInMemory = true;
            cpar.GenerateExecutable = false;
            cpar.ReferencedAssemblies.Add("system.dll");
            cpar.ReferencedAssemblies.Add("ComputingMath.dll");

            string src = "using System;" +
             "class myclass : ComputingMath.Parsing.Function" +
             "{" +
             "public myclass(){}" +
             "public override double evaluate(double[] x)" +
             "{" +
             "return " + expression + ";" +
             "}" +
             "}";

            System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, src);

            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                throw new ParsingErrorException(ce.ErrorText);
            }

            if ((cr.Errors.Count == 0) && (cr.CompiledAssembly != null))
            {
                Type ObjType = cr.CompiledAssembly.GetType("myclass");
                try
                {
                    if (ObjType != null)
                    {
                        myFunction = (Function)Activator.CreateInstance(ObjType);
                    }
                }
                catch (Exception exception)
                {
                    throw new ParsingErrorException("Unexpected error due to parsing function!", exception);
                }
            }
            else
            {
                throw new ParsingErrorException("Error parsing function!");
            }
        }