/// <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/GSP_WorkflowWebservice/common.asmx","Genersoft.Platform.Service.Workflow","Common","GetToolType",new object[]{"1"}); 
        /// </code> 
        /// </example> 
        public static object InvokeWebservice(string url, string @namespace, string classname, string methodname, params 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 icc = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults cr = 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));
            }
        }
        /// <summary<
        /// 构造函数
        /// </summary<
        /// <param name="url"<</param<
        public WebServiceAgent(string url)
        {
            XmlTextReader reader = new XmlTextReader(url + "?wsdl");

            //创建和格式化 WSDL 文档
            ServiceDescription sd = ServiceDescription.Read(reader);

            //创建客户端代理代理类
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, null, null);

            //使用 CodeDom 编译客户端代理类
            CodeNamespace   cn  = new CodeNamespace(CODE_NAMESPACE);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            CompilerResults    cr = icc.CompileAssemblyFromDom(cp, ccu);

            agentType = cr.CompiledAssembly.GetTypes()[0];
            agent     = Activator.CreateInstance(agentType);
        }
        public Assembly CreateAssembly(string codeNamespace, IDictionary <string, Dictionary <string, object> > typePropsDictionary)
        {
            var csc        = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new CompilerParameters(new[] { "System.dll", "System.Core.dll" });

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

            var compileUnit = new System.CodeDom.CodeCompileUnit();

            var ns = new CodeNamespace(codeNamespace);

            compileUnit.Namespaces.Add(ns);

            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));


            foreach (var typeProps in typePropsDictionary)
            {
                var classType = new CodeTypeDeclaration(typeProps.Key);
                classType.Attributes = MemberAttributes.Public;
                ns.Types.Add(classType);

                foreach (var prop in typeProps.Value)
                {
                    if (prop.Value is Type type)
                    {
                        var fieldName = "_" + prop.Key;
                        var field     = new CodeMemberField(type, fieldName);
                        classType.Members.Add(field);

                        var property = new CodeMemberProperty();
                        property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                        property.Type       = new CodeTypeReference(type);
                        property.Name       = prop.Key;
                        property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName)));
                        property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodePropertySetValueReferenceExpression()));
                        classType.Members.Add(property);
                    }
                    else if (prop.Value is CodeTypeReference codeType)
                    {
                        var fieldName = "_" + prop.Key;
                        var field     = new CodeMemberField(codeType, fieldName);
                        classType.Members.Add(field);

                        var property = new CodeMemberProperty();
                        property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                        property.Type       = codeType;
                        property.Name       = prop.Key;
                        property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName)));
                        property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodePropertySetValueReferenceExpression()));
                        classType.Members.Add(property);
                    }
                }
            }
            var results = csc.CompileAssemblyFromDom(parameters, compileUnit);

            return(results.CompiledAssembly);
        }
Exemple #4
0
        /// <summary<
        /// Constructor
        /// </summary<
        /// <param name="url"<</param<
        public JstWebServiceAgent(string url)
        {
            try
            {
                XmlTextReader reader = new XmlTextReader(url + "?wsdl");

                //建立 WSDL格式文档
                ServiceDescription sd = ServiceDescription.Read(reader);

                //客户端代理
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, null, null);

                //使用CodeDom 动态编译代理类
                CodeNamespace   cn  = new CodeNamespace(CODE_NAMESPACE);
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
                CompilerParameters cp = new CompilerParameters();
                CompilerResults    cr = icc.CompileAssemblyFromDom(cp, ccu);
                agentType = cr.CompiledAssembly.GetTypes()[0];
                agent     = Activator.CreateInstance(agentType);
                WriteTextLog("日志", "初始化成功", DateTime.Now);
            }
            catch (Exception ex)
            {
                WriteTextLog("错误", ex.ToString(), DateTime.Now);
                throw;
            }
        }
        public static void service_info_methods()
        {
            uri = new Uri("http://localhost:60377/Service1.asmx?wsdl"); 
            WebRequest webRequest = WebRequest.Create(uri);
            System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
            // Get a WSDL file describing a service
            ServiceDescription sd = ServiceDescription.Read(requestStream);
            string sdName = sd.Services[0].Name;

            // Initialize a service description servImport
            ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
            servImport.AddServiceDescription(sd, String.Empty, String.Empty);
            servImport.ProtocolName = "Soap";
            servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

            CodeNamespace nameSpace = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            codeCompileUnit.Namespaces.Add(nameSpace);
            // Set Warnings
            ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

            if (warnings == 0)
            {
                StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
                CompilerParameters param = new CompilerParameters(assemblyReferences);
                param.GenerateExecutable = false;
                param.GenerateInMemory = true;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel = 4;

                CompilerResults results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                Assembly assembly = results.CompiledAssembly;
                service = assembly.GetType(sdName);

                methodInfo = service.GetMethods();

                int c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                        break;
                    c++;
                }
                listurl = new string[c]; c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                        break;
                    listurl[c++] = t.Name;
                }

            }

        }
Exemple #6
0
        /*
         * 优点:不用引用,通过网址,目标命名空间,调用WebServices,用于主站向子站请求数据
         * 缺点:使用上不如直接Web引用进来易用,如果只是单个并确定的,最好引用进来
         */
        /// <summary>
        /// 通过反射完成调用
        /// </summary>
        public static object InvokeWebSer(string url, string @namespace, string classname, string methodname, object[] args)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            string URL = string.Empty;

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

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

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

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

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

            System.Reflection.MethodInfo mi = t.GetMethod(methodname);
            return(mi.Invoke(obj, args));
        }
Exemple #7
0
        public static Action <TextWriter, T> Compile <T>(TextReader template)
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());

            host.DefaultBaseClass = string.Format("Veil.Benchmark.RazorBase<{0}>", typeof(T) == typeof(object) ? "dynamic" : typeof(T).FullName);
            host.DefaultNamespace = "VeilRazor";
            host.DefaultClassName = "Template";

            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.IO");
            host.NamespaceImports.Add("Microsoft.CSharp.RuntimeBinder");

            var engine    = new RazorTemplateEngine(host);
            var genResult = engine.GenerateCode(template);

            using (var provider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                var parameters = new CompilerParameters(new[] {
                    GetAssemblyPath(typeof(T)),
                    GetAssemblyPath(typeof(Microsoft.CSharp.RuntimeBinder.Binder)),
                    GetAssemblyPath(typeof(RazorBase <>)),
                    GetAssemblyPath(typeof(INotifyPropertyChanged)),
                    GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite))
                });
                parameters.GenerateInMemory = true;

                var compileResult = provider.CompileAssemblyFromDom(parameters, genResult.GeneratedCode);

                if (compileResult.Errors.HasErrors)
                {
                    throw new InvalidOperationException(compileResult.Errors[0].ErrorText);
                }

                var viewType = compileResult.CompiledAssembly.GetType("VeilRazor.Template");
                var view     = Expression.Variable(viewType, "view");
                var init     = viewType.GetMethod("Initialize");
                var exec     = viewType.GetMethod("Execute");
                var writer   = Expression.Parameter(typeof(TextWriter));
                var model    = Expression.Parameter(typeof(T));

                return(Expression.Lambda <Action <TextWriter, T> >(Expression.Block(
                                                                       new[] { view },
                                                                       new Expression[] {
                    Expression.Assign(view, Expression.New(viewType)),
                    Expression.Call(view, init, writer, model),
                    Expression.Call(view, exec)
                }
                                                                       ), writer, model).Compile());
            }
        }
Exemple #8
0
        // Returns an instance of the razor template, compiled from the file stored as an embedded resource.
        // The first time this method is executed, the Razor template is compiled and stored.
        // This method will throw an InvalidDataException if the template contains syntax errors.
        public TemplateBase CreateRazorTemplateInstance()
        {
            if (templateType == null)
            {
                var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
                host.DefaultBaseClass = typeof(TemplateBase).FullName;
                host.DefaultNamespace = "RazorOutput";
                host.DefaultClassName = "Template";
                host.NamespaceImports.Add("System");

                GeneratorResults razorResult = null;

                var templateStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Curtsy.Resources.curtsy.cshtml");

                if (templateStream == null)
                    throw new FileNotFoundException("Could not find embedded resource 'Curtsy.Resources.curtsy.cshtml'");

                using (var reader = new StreamReader(templateStream))
                {
                    razorResult = new RazorTemplateEngine(host).GenerateCode(reader);
                }

                var compilerParams = new CompilerParameters
                {
                    GenerateInMemory = true,
                    GenerateExecutable = false,
                    IncludeDebugInformation = false,
                    CompilerOptions = "/target:library /optimize"
                };
                compilerParams.ReferencedAssemblies.Add(typeof(Program).Assembly.CodeBase.Replace("file:///", "").Replace('/', Path.DirectorySeparatorChar));

                var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                var results = codeProvider.CompileAssemblyFromDom(compilerParams, razorResult.GeneratedCode);

                if (results.Errors.HasErrors)
                {
                    StringBuilder errors = new StringBuilder();
                    foreach (var err in results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning))
                        errors.AppendFormat("Error compiling template: ({0}, {1}) {2}", err.Line, err.Column, err.ErrorText);

                    throw new InvalidDataException(errors.ToString());
                }

                templateType = results.CompiledAssembly.GetType("RazorOutput.Template");
            }

            return (TemplateBase)Activator.CreateInstance(templateType);
        }
Exemple #9
0
        public static byte[] GenerateAssembly(string namespaceName, string className, params CodeMemberMethod[] methods)
        {
            CodeCompileUnit     unit  = new CodeCompileUnit();
            CodeNamespace       space = new CodeNamespace(namespaceName);
            CodeTypeDeclaration type  = new CodeTypeDeclaration(className);

            type.Attributes     = MemberAttributes.Static | MemberAttributes.Public;
            type.TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed;

            type.Members.AddRange(methods);
            space.Types.Add(type);
            unit.Namespaces.Add(space);

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

            System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
            options.IncludeDebugInformation = false;
            options.GenerateExecutable      = false;

            options.ReferencedAssemblies.Add(typeof(int).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location);

            System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromDom(options, unit);

            System.CodeDom.Compiler.CodeGeneratorOptions ops = new System.CodeDom.Compiler.CodeGeneratorOptions();
            ops.IndentString  = "\t";
            ops.VerbatimOrder = true;
            ops.BracingStyle  = "C";

            StringWriter text = new StringWriter();

            provider.GenerateCodeFromCompileUnit(unit, text, ops);
            string code = text.ToString();

            if (results.Errors.HasErrors)
            {
                string errors = "";
                foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
                {
                    errors += error.ToString() + Environment.NewLine;
                }
                throw new InvalidOperationException(errors);
            }

            byte[] data = File.ReadAllBytes(results.PathToAssembly);
            File.Delete(results.PathToAssembly);
            return(data);
        }
Exemple #10
0
        /// <summary<
        /// 设置代理
        /// </summary<
        /// <param name="url"<</param<
        public static void SetWebServiceAgent(string url)
        {
            XmlTextReader reader = new XmlTextReader(url + "?wsdl");

            //创建和格式化 WSDL 文档
            ServiceDescription sd = ServiceDescription.Read(reader);

            //创建客户端代理代理类
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, null, null);

            //使用 CodeDom 编译客户端代理类
            CodeNamespace   cn  = new CodeNamespace(CODE_NAMESPACE);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();

            cp.GenerateExecutable = false;
            //cp.OutputAssembly = "temp.dll";//输出程序集的名称
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.XML.dll");
            cp.ReferencedAssemblies.Add("System.Web.Services.dll");
            cp.ReferencedAssemblies.Add("System.Data.dll");
            CompilerResults cr = icc.CompileAssemblyFromDom(cp, 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());
            }
            //生成代理实例
            string key       = url.ToLower();
            Type   agentType = cr.CompiledAssembly.GetTypes()[0]; //编译生成程序集Type

            _agentType.Add(key, agentType);
            object agent = Activator.CreateInstance(agentType); //生成代理实例

            _agent.Add(key, agent);
        }
		public static byte[] GenerateAssembly(string namespaceName, string className, params CodeMemberMethod[] methods)
		{
			CodeCompileUnit unit = new CodeCompileUnit();
			CodeNamespace space = new CodeNamespace(namespaceName);
			CodeTypeDeclaration type = new CodeTypeDeclaration(className);

			type.Attributes = MemberAttributes.Static | MemberAttributes.Public;
			type.TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed;

			type.Members.AddRange(methods);
			space.Types.Add(type);
			unit.Namespaces.Add(space);

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

			System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
			options.IncludeDebugInformation = false;
			options.GenerateExecutable = false;

			options.ReferencedAssemblies.Add(typeof(int).Assembly.Location);
			options.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location);

			System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromDom(options,unit);

			System.CodeDom.Compiler.CodeGeneratorOptions ops = new System.CodeDom.Compiler.CodeGeneratorOptions();
			ops.IndentString = "\t";
			ops.VerbatimOrder = true;
			ops.BracingStyle = "C";

			StringWriter text = new StringWriter();
			provider.GenerateCodeFromCompileUnit(unit, text, ops);
			string code = text.ToString();

			if (results.Errors.HasErrors)
			{
				string errors = "";
				foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
				{
					errors += error.ToString() + Environment.NewLine;
				}
				throw new InvalidOperationException(errors);
			}
			
			byte[] data = File.ReadAllBytes(results.PathToAssembly);
			File.Delete(results.PathToAssembly);
			return data;
		}
        /// < summary> 
        /// 动态调用web服务 
        /// < /summary> 
        /// < param name="url">WSDL服务地址< /param> 
        /// < param name="classname">类名< /param> 
        /// < param name="methodname">方法名< /param> 
        /// < param name="args">参数< /param> 
        /// < returns>< /returns> 
        public static object Invoke(string url, string classname, string methodname, object[] args)
        {
            string ns = "EnterpriseServerBase.WebService.DynamicWebCalling";
            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceInvoker.GetWsClassName(url);
            }
            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(ns);
            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 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 = csc.CompileAssemblyFromDom(cplist, ccu);
            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new NHExt.Runtime.Exceptions.RuntimeException("调用WebService开始编译发生错误:" + sb.ToString());
            }
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            Type t = assembly.GetType(ns + "." + classname, true, true);
            object obj = Activator.CreateInstance(t);
            System.Reflection.MethodInfo mi = t.GetMethod(methodname);
            return mi.Invoke(obj, args);
        }
        public Assembly GetServiceInspector(Stream stream)
        {
            var wsdlRequestStream = stream;

            var sd       = ServiceDescription.Read(wsdlRequestStream);
            var sdImport = new ServiceDescriptionImporter();

            sdImport.AddServiceDescription(sd, String.Empty, String.Empty);
            sdImport.ProtocolName          = "Soap";
            sdImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;
            var codeNameSpace   = new CodeNamespace();
            var codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(codeNameSpace);
            var warnings = sdImport.Import(codeNameSpace, codeCompileUnit);

            if (warnings == 0)
            {
                var stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                var prov         = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(codeNameSpace, stringWriter, new CodeGeneratorOptions());
                //Compile the assembly
                var assemblyReferences = new string[2] {
                    "System.Web.Services.dll", "System.Xml.dll"
                };
                var param = new CompilerParameters(assemblyReferences)
                {
                    GenerateExecutable    = false,
                    GenerateInMemory      = true,
                    TreatWarningsAsErrors = false,
                    WarningLevel          = 4
                };
                var results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                var assembly = results.CompiledAssembly;

                return(assembly);
            }
            else
            {
                return(null);
            }
        }
        private static Type CompileCode(CodeCompileUnit compileUnit)
        {
            Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters compilerParameters = new CompilerParameters();

            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            string currentBinLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.Entity.Interfaces.dll"));
            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.Platform.dll"));
            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.SData.Client.dll"));
            compilerParameters.ReferencedAssemblies.Add(Path.Combine(currentBinLocation, "Sage.SalesLogix.Client.dll"));

            CompilerResults result = codeProvider.CompileAssemblyFromDom(compilerParameters, compileUnit);

            if (result.Errors.Count > 0)
                throw new InvalidOperationException(result.Errors[0].ErrorText);

            //The only type within the Assembly is the type requested here.
            return result.CompiledAssembly.GetTypes()[0];
        }
Exemple #15
0
        private static Type BuildAdapter(Type type, string name, IEnumerable <PropertyColumn> columns)
        {
            CodeDomProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();

            CodeCompileUnit    ccu   = BuildCompileUnit(type, name, columns);
            CompilerParameters param = new CompilerParameters();

            List <Type> allTypes = new TypeReflector().GetAllTypes(type);

            foreach (Type t in allTypes)
            {
                string assemblyPath = t.Assembly.Location;
                if (param.ReferencedAssemblies.Contains(assemblyPath))
                {
                    continue;
                }
                param.ReferencedAssemblies.Add(assemblyPath);
            }

            param.ReferencedAssemblies.Add(typeof(IDataTableAdapter <>).Assembly.Location);
            param.ReferencedAssemblies.Add(typeof(DataTable).Assembly.Location);
            param.ReferencedAssemblies.Add(typeof(IListSource).Assembly.Location);
            param.ReferencedAssemblies.Add(typeof(IXmlSerializable).Assembly.Location);

#if DEBUG
            param.TempFiles.KeepFiles     = true;
            param.IncludeDebugInformation = true;
#endif
            CompilerResults cr = cdp.CompileAssemblyFromDom(param, ccu);

            if (cr.Errors.Count > 0)
            {
                foreach (object error in cr.Errors)
                {
                    global::System.Diagnostics.Debug.WriteLine(error);
                }
                throw new Exception(Resources.CodeGenerationError);
            }
            return(cr.CompiledAssembly.GetType(_namespace + "." + name));
        }
        private bool CompileAssembly(out Assembly outputAssembly, out string outpurFilePath)
        {
            CodeNamespace   nameSpace       = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(nameSpace);
            // Set Warnings
            ServiceDescriptionImportWarnings warnings = ServiceImporter.Import(nameSpace, codeCompileUnit);

            if (warnings == 0 || warnings.ToString().EndsWith("Ignored"))
            {
                StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                // Compile the assembly with the appropriate references
                string[] assemblyReferences = new string[5] {
                    "System.Web.Services.dll", "System.Xml.dll", "System.dll", "System.Web.dll", "System.Data.dll"
                };

                CompilerParameters param = new CompilerParameters(assemblyReferences);
                param.GenerateExecutable    = false;
                param.GenerateInMemory      = false;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel          = 4;

                CompilerResults results = new CompilerResults(new TempFileCollection());
                results        = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                outpurFilePath = results.PathToAssembly;
                outputAssembly = results.CompiledAssembly;
                return(true);
            }
            else
            {
                outpurFilePath = warnings.ToString();
                outputAssembly = null;
                return(false);
            }
        }
Exemple #17
0
        //### Helpers & Setup

        // Setup the Razor templating engine so that we can quickly pass the data in
        // and generate HTML.
        //
        // The file `Resources\Nocco.cshtml` is read and compiled into a new dll
        // with a type that extends the `TemplateBase` class. This new assembly is
        // loaded so that we can create an instance and pass data into it
        // and generate the HTML.
        private static Type SetupRazorTemplate()
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());

            host.DefaultBaseClass = typeof(TemplateBase).FullName;
            host.DefaultNamespace = "RazorOutput";
            host.DefaultClassName = "Template";
            host.NamespaceImports.Add("System");

            GeneratorResults razorResult = null;

            using (var reader = new StreamReader(Path.Combine(_executingDirectory, "Resources", "Nocco.cshtml"))) {
                razorResult = new RazorTemplateEngine(host).GenerateCode(reader);
            }

            var compilerParams = new CompilerParameters {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                CompilerOptions         = "/target:library /optimize"
            };

            compilerParams.ReferencedAssemblies.Add(typeof(Nocco).Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\"));

            var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            var results      = codeProvider.CompileAssemblyFromDom(compilerParams, razorResult.GeneratedCode);

            // Check for errors that may have occurred during template generation
            if (results.Errors.HasErrors)
            {
                foreach (var err in results.Errors.OfType <CompilerError>().Where(ce => !ce.IsWarning))
                {
                    Console.WriteLine("Error Compiling Template: ({0}, {1}) {2}", err.Line, err.Column, err.ErrorText);
                }
            }

            return(results.CompiledAssembly.GetType("RazorOutput.Template"));
        }
        public static Assembly CompileInMemory(CodeCompileUnit[] codeCompileUnits, string[] assemblyNames)
        {
            // TODO: better way?
            var codeProvider   = new Microsoft.CSharp.CSharpCodeProvider();
            var compileOptions = new CompilerParameters();

            compileOptions.GenerateInMemory = true;

            compileOptions.ReferencedAssemblies.AddRange(assemblyNames);
            CompilerResults results = codeProvider.CompileAssemblyFromDom(compileOptions, codeCompileUnits);

            if (results.Errors.Count > 0)
            {
                List <string> errors = new List <string>();
                foreach (CompilerError error in results.Errors)
                {
                    errors.Add(string.Format("{0} Line {1} Column {2}", error.ErrorText, error.Line, error.Column));
                }

                StringBuilder sb = new StringBuilder();
                foreach (string error in errors)
                {
                    sb.AppendFormat("\n\n{0}", error);
                }
                string errorText = sb.ToString();

                throw CodeCompilerException.NewFormat(
                          results.Errors,
                          codeCompileUnits,
                          codeProvider,
                          "Errors in compiling CodeCompileUnits: {0}",
                          errorText
                          );
            }

            return(results.CompiledAssembly);
        }
Exemple #19
0
        public void TestSpecific(string str, object[] result)
        {
            if (compres == null)
            {
                Protocol protocol = Protocol.Parse(str);
                var      codegen  = new CodeGen();
                codegen.AddProtocol(protocol);
                var compileUnit = codegen.GenerateCode();

                // add a constructor to the main class using the passed assignment statements
                CodeTypeDeclaration ctd         = compileUnit.Namespaces[0].Types[(int)result[0]];
                CodeConstructor     constructor = new CodeConstructor();
                constructor.Attributes = MemberAttributes.Public;
                CodeSnippetExpression snippet = new CodeSnippetExpression((string)result[2]);
                constructor.Statements.Add(snippet);
                ctd.Members.Add(constructor);

                // add a function to the main class to populate the data
                // This has been moved from constructor, as it was causing some tests to pass that shouldn't when referencing a blank object on READ.

                CodeMemberMethod method = new CodeMemberMethod();
                method.Attributes = MemberAttributes.Public;
                method.Name       = "Populate";
                CodeSnippetExpression snippet2 = new CodeSnippetExpression((string)result[3]);
                method.Statements.Add(snippet2);
                ctd.Members.Add(method);



                // compile
                var comparam = new CompilerParameters(new string[] { "netstandard.dll" });
                comparam.ReferencedAssemblies.Add("System.dll");
                comparam.ReferencedAssemblies.Add(Path.Combine(TestContext.CurrentContext.TestDirectory, "Avro.dll"));
                comparam.GenerateInMemory = true;
                var ccp   = new Microsoft.CSharp.CSharpCodeProvider();
                var units = new CodeCompileUnit[] { compileUnit };
                compres = ccp.CompileAssemblyFromDom(comparam, units);
                Assert.IsNotNull(compres);
                if (compres.Errors.Count > 0)
                {
                    for (int i = 0; i < compres.Errors.Count; i++)
                    {
                        Console.WriteLine(compres.Errors[i]);
                    }
                }
                Assert.IsTrue(compres.Errors.Count == 0);
            }

            // create record
            ISpecificRecord rec = compres.CompiledAssembly.CreateInstance((string)result[1]) as ISpecificRecord;

            // Call populate to put some data in it.
            Type       recType    = rec.GetType();;
            MethodInfo methodInfo = recType.GetMethod("Populate");

            methodInfo.Invoke(rec, null);

            var x1 = compres.CompiledAssembly.FullName;

            Assert.IsFalse(rec == null);

            // serialize
            var stream = serialize(rec.Schema, rec);

            // deserialize
            var rec2 = deserialize <ISpecificRecord>(stream, rec.Schema, rec.Schema);

            Assert.IsFalse(rec2 == null);
            AssertSpecificRecordEqual(rec, rec2);
        }
Exemple #20
0
        public static Assembly CreateAssemblyCached(string wsdlUrl, ref string className)
        {
            string key = AddWSDL(wsdlUrl);

            lock (_lock)
            {
                // Query cache first.
                if (CacheAssembly.ContainsKey(key))
                {
                    if (CacheTimeouts.ContainsKey(key))
                    {
                        if ((DateTime.UtcNow - CacheTimeouts[key]).TotalMinutes <= CACHE_TIME_OUT)
                        {
                            if (false == string.IsNullOrEmpty(CacheServices[key]))
                            {
                                className = CacheServices[key];
                            }
                            return(CacheAssembly[key]);
                        }
                    }
                }

                try
                {
                    //获取WSDL
                    WebClient                  wc     = new WebClient();
                    Stream                     stream = wc.OpenRead(key);
                    ServiceDescription         sd     = ServiceDescription.Read(stream);
                    ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                    // set className according to service name
                    if (sd.Services.Count > 0)
                    {
                        className = sd.Services[0].Name;
                    }
                    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 = csc.CompileAssemblyFromDom(cplist, ccu);
                    if (true == cr.Errors.HasErrors)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(System.Environment.NewLine);
                        }
                        throw new Exception(sb.ToString());
                    }



                    //生成代理实例,并调用方法
                    System.Reflection.Assembly assembly = cr.CompiledAssembly;
                    // add to cache
                    CacheAssembly[key] = assembly;
                    CacheTimeouts[key] = DateTime.UtcNow;
                    CacheServices[key] = className;
                    return(assembly);
                }
                catch (Exception ex)
                {
                    if (null == ex.InnerException)
                    {
                        throw new Exception(ex.Message, new Exception(ex.StackTrace));
                    }
                    else
                    {
                        throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
                    }
                }
            }
        }
Exemple #21
0
        private void OnMESCall1()
        {
            try
            {
                //WEB服务地址
                string url = this.textBoxMesAddr.Text;
                //客户端代理服务命名空间,可以设置成需要的值。
                string ns = string.Format("JCJProxMES");
                //获取WSDL
                WebClient          wc        = new WebClient();
                Stream             stream    = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd        = ServiceDescription.Read(stream);//服务的描述信息都可以通过ServiceDescription获取
                string             classname = sd.Services[0].Name;

                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(ns);

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

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

                //编译代理类
                System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                if (cr.Errors.HasErrors == true)
                {
                    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(ns + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);

                //实例化方法
                System.Reflection.MethodInfo helloWorld = t.GetMethod("DxTestDataUpload");

                //设置参数

                object device         = textBox1.Text.Trim();
                object workstation_sn = textBox2.Text.Trim();
                object emp_no         = textBox3.Text.Trim();
                object mo_number      = textBox4.Text.Trim();
                object container_no   = textBox5.Text.Trim();
                object product_sn     = textBox6.Text.Trim();
                object union_list     = textBox7.Text.Trim();


                object mod_level = textBox8.Text.Trim();
                object test_re   = textBox9.Text.Trim();
                object test_val  = textBox10.Text.Trim();

                object   test_time = textBox11.Text.Trim();
                object   mark      = textBox12.Text.Trim();
                object   m_flag    = int.Parse(textBox13.Text.Trim());
                object[] addParams = new object[] { m_flag, device, workstation_sn, emp_no, mo_number, container_no, product_sn, union_list, mod_level, test_re, test_val, test_time, mark };

                //参数赋值并调用方法
                object helloWorldReturn = helloWorld.Invoke(obj, addParams);

                Console.WriteLine(helloWorldReturn.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        public Type GetProxyTypeForStateInterface()
        {
            if (_proxyTypeCache == null)
            {
                List<Type> typesRequired = new List<Type>();
                typesRequired.Add(_interfaceType);

                // Create a code compile unit and a namespace
                CodeCompileUnit ccu = new CodeCompileUnit();
                CodeNamespace ns = new CodeNamespace("Esmf.StateTypes");

                // Add some imports statements to the namespace
                ns.Imports.Add(new CodeNamespaceImport("System"));
                // ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));

                // Add the namespace to the code compile unit
                ccu.Namespaces.Add(ns);

                string implementationTypeName = _interfaceName.StartsWith("I", StringComparison.OrdinalIgnoreCase) ? _interfaceName.Substring(1) : String.Format("{0}Implementation", _interfaceName);
                CodeTypeDeclaration ctd = new CodeTypeDeclaration(implementationTypeName);
                ctd.BaseTypes.Add(_interfaceType);
                ctd.BaseTypes.Add(typeof(IStateObjectConnections));

                ns.Types.Add(ctd);

                foreach (StateFieldStructure field in _fields)
                {
                    if (!typesRequired.Contains(field.Type))
                    {
                        typesRequired.Add(field.Type);
                    }

                    if (field.Dimensions.Count == 0)
                    {
                        CodeTypeReference tt = new CodeTypeReference(field.Type);

                        CodeTypeReference ttGetter = new CodeTypeReference(typeof(NonDimensionalFieldGetter<>));
                        ttGetter.TypeArguments.Add(tt);
                        string _fieldGetter = String.Format("_{0}FieldGetter", field.Name);
                        CodeMemberField newGetterField = new CodeMemberField(ttGetter, _fieldGetter);
                        ctd.Members.Add(newGetterField);

                        CodeMemberProperty p = new CodeMemberProperty();
                        p.Name = String.Format("{0}.{1}", _interfaceType, field.Name);
                        p.Type = tt;
                        p.Attributes -= MemberAttributes.Private;
                        CodeStatementCollection getStatements = p.GetStatements;

                        getStatements.Add(
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    new CodeFieldReferenceExpression(
                                        new CodeThisReferenceExpression(),
                                            _fieldGetter),
                                        CodeBinaryOperatorType.IdentityInequality,
                                        new CodePrimitiveExpression(null)),
                                    new CodeStatement[] { new CodeMethodReturnStatement(new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), _fieldGetter))) },
                                    new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(InvalidOperationException)))) }));

                        if (field.CanWrite)
                        {
                            CodeTypeReference ttSetter = new CodeTypeReference(typeof(NonDimensionalFieldSetter<>));
                            ttSetter.TypeArguments.Add(tt);
                            string _fieldSetter = String.Format("_{0}FieldSetter", field.Name);
                            CodeMemberField newSetterField = new CodeMemberField(ttSetter, _fieldSetter);
                            ctd.Members.Add(newSetterField);

                            CodeStatementCollection setStatements = p.SetStatements;

                            setStatements.Add(
                                new CodeConditionStatement(
                                    new CodeBinaryOperatorExpression(
                                        new CodeFieldReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                                _fieldSetter),
                                            CodeBinaryOperatorType.IdentityInequality,
                                            new CodePrimitiveExpression(null)),
                                        new CodeStatement[] { new CodeExpressionStatement(new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), _fieldSetter), new CodeExpression[] { new CodePropertySetValueReferenceExpression() })) },
                                        new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(InvalidOperationException)))) }));

                        }

                        ctd.Members.Add(p);

                    }
                    else if (field.Dimensions.Count > 0)
                    {
                        CodeTypeReference tt;
                        if (field.CanWrite)
                        {
                            if (field.Dimensions.Count == 1)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IVariable1Dimensional<,>));
                            }
                            else if (field.Dimensions.Count == 2)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IVariable2Dimensional<,,>));
                            }
                            else
                            {
                                throw new InvalidOperationException("Can't have parameters with more than 2 dimensions");
                            }
                        }
                        else
                        {
                            if (field.Dimensions.Count == 1)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IParameter1Dimensional<,>));
                            }
                            else if (field.Dimensions.Count == 2)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IParameter2Dimensional<,,>));
                            }
                            else
                            {
                                throw new InvalidOperationException("Can't have fields with more than 2 dimensions");
                            }
                        }

                        foreach (StateFieldDimensionStructure sfds in field.Dimensions)
                        {
                            tt.TypeArguments.Add(sfds.Type);

                            if (!typesRequired.Contains(sfds.Type))
                            {
                                typesRequired.Add(sfds.Type);
                            }
                        }
                        tt.TypeArguments.Add(field.Type);

                        string fieldName = String.Format("_{0}Field", field.Name);
                        CodeMemberField newField = new CodeMemberField(tt, fieldName);
                        ctd.Members.Add(newField);

                        CodeMemberProperty p = new CodeMemberProperty();
                        p.Name = String.Format("{0}.{1}", _interfaceType, field.Name);
                        p.Type = tt;
                        p.Attributes -= MemberAttributes.Private;
                        CodeStatementCollection statements = p.GetStatements;

                        statements.Add(
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    new CodeFieldReferenceExpression(
                                        new CodeThisReferenceExpression(),
                                            fieldName),
                                        CodeBinaryOperatorType.IdentityInequality,
                                        new CodePrimitiveExpression(null)),
                                    new CodeStatement[] { new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName)) },
                                    new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(InvalidOperationException)))) }));
                        ctd.Members.Add(p);
                    }

                }

                GenerateCodeForIStateObjectConnection(ctd);

                CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                CompilerParameters cp = new CompilerParameters();
                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add(typeof(IParameter1Dimensional<,>).Module.FullyQualifiedName);

                List<string> modules = new List<string>();
                foreach (Type t in typesRequired)
                {
                    if (!modules.Contains(t.Module.FullyQualifiedName))
                    {
                        modules.Add(t.Module.FullyQualifiedName);
                    }
                }

                foreach (string s in modules)
                {
                    cp.ReferencedAssemblies.Add(s);
                }

                cp.GenerateInMemory = true;
                string assemblyDirectory = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Temp");
                if (!Directory.Exists(assemblyDirectory))
                {
                    Directory.CreateDirectory(assemblyDirectory);
                }
                cp.OutputAssembly = Path.Combine(assemblyDirectory, string.Format("AutoGenerated{0}.dll", Guid.NewGuid()));
                CompilerResults results = provider.CompileAssemblyFromDom(cp, ccu);
                if (results.Errors.HasErrors)
                {
                    foreach (CompilerError err in results.Errors)
                    {
                        Console.WriteLine();
                        Console.WriteLine(err);
                    }
                }

                //CodeDomProvider provider2 = new Microsoft.CSharp.CSharpCodeProvider();
                //using (System.IO.TextWriter output = System.IO.File.CreateText(@"C:\Users\davidanthoff\Documents\Visual Studio 2005\Projects\test.cs"))
                //{
                //    provider2.GenerateCodeFromCompileUnit(ccu, output, new CodeGeneratorOptions());
                //}

                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

                _proxyTypeCache = results.CompiledAssembly.GetType("Esmf.StateTypes." + implementationTypeName);

                AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);

                return _proxyTypeCache;
            }
            else
            {
                return _proxyTypeCache;
            }
        }
Exemple #23
0
        //### Helpers & Setup
        // Setup the Razor templating engine so that we can quickly pass the data in
        // and generate HTML.
        //
        // The file `Resources\Nocco.cshtml` is read and compiled into a new dll
        // with a type that extends the `TemplateBase` class. This new assembly is
        // loaded so that we can create an instance and pass data into it
        // and generate the HTML.
        private static Type SetupRazorTemplate()
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
            host.DefaultBaseClass = typeof(TemplateBase).FullName;
            host.DefaultNamespace = "RazorOutput";
            host.DefaultClassName = "Template";
            host.NamespaceImports.Add("System");

            GeneratorResults razorResult = null;
            using (var reader = new StreamReader(Path.Combine(_executingDirectory, "Resources", "Nocco.cshtml"))) {
                razorResult = new RazorTemplateEngine(host).GenerateCode(reader);
            }

            var compilerParams = new CompilerParameters {
                GenerateInMemory = true,
                GenerateExecutable = false,
                IncludeDebugInformation = false,
                CompilerOptions = "/target:library /optimize"
            };
            compilerParams.ReferencedAssemblies.Add(typeof(Nocco).Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\"));

            var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults results = codeProvider.CompileAssemblyFromDom(compilerParams, razorResult.GeneratedCode);

            // Check for errors that may have occurred during template generation
            if (results.Errors.HasErrors) {
                foreach (var err in results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning))
                    Console.WriteLine("Error Compiling Template: ({0}, {1}) {2}", err.Line, err.Column, err.ErrorText);
            }

            return results.CompiledAssembly.GetType("RazorOutput.Template");
        }
Exemple #24
0
        private void DynamicInvocation()
        {
            try
            {
                uri = new Uri(Session["Deviceurl"].ToString() + "?wsdl");
            }
            catch { uri = new Uri("http://localhost:60377/Service1.asmx?wsdl"); }
            WebRequest webRequest = WebRequest.Create(uri);

            System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
            // Get a WSDL file describing a service
            ServiceDescription sd     = ServiceDescription.Read(requestStream);
            string             sdName = sd.Services[0].Name;

            // Initialize a service description servImport
            ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();

            servImport.AddServiceDescription(sd, String.Empty, String.Empty);
            servImport.ProtocolName          = "Soap";
            servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

            CodeNamespace   nameSpace       = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(nameSpace);
            // Set Warnings
            ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

            if (warnings == 0)
            {
                StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                string[] assemblyReferences = new string[2] {
                    "System.Web.Services.dll", "System.Xml.dll"
                };
                CompilerParameters param = new CompilerParameters(assemblyReferences);
                param.GenerateExecutable    = false;
                param.GenerateInMemory      = true;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel          = 4;

                CompilerResults results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                Assembly assembly = results.CompiledAssembly;
                service               = assembly.GetType(sdName);
                Session["service"]    = service;
                methodInfo            = service.GetMethods();
                Session["methodInfo"] = methodInfo;
                int c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                    {
                        break;
                    }
                    c++;
                }
                listurl = new string[c]; c = 0;
                foreach (MethodInfo t in methodInfo)
                {
                    if (t.Name == "Discover")
                    {
                        break;
                    }
                    listurl[c++] = t.Name;
                }

                Session["listurl"] = listurl;
            }
        }
Exemple #25
0
        private void RunText1(string codes)
        {
            List <string> UsingList = new List <string>()
            {
                "System",
                "System.Windows.Forms",
            };
            List <string> ImportList = new List <string>()
            {
                "System.dll",
                "System.Windows.Forms.dll",
            };

            CodeMemberMethod pMethod = new CodeMemberMethod();

            pMethod.Name       = "TestFunction";
            pMethod.Attributes = MemberAttributes.Public;
            pMethod.Parameters.Add(new
                                   CodeParameterDeclarationExpression(typeof(string), "msg"));
            pMethod.ReturnType = new CodeTypeReference(typeof(void));
            pMethod.Statements.Add(new CodeSnippetStatement(codes));
            //new CodeSnippetExpression(" MessageBox.Show(msg);"));

            CodeTypeDeclaration pClass =
                new System.CodeDom.CodeTypeDeclaration("MyTestClass");

            pClass.Attributes = MemberAttributes.Public;
            pClass.Members.Add(pMethod);

            CodeNamespace pNamespace = new CodeNamespace("CodeTextExecTest");

            pNamespace.Types.Add(pClass);
            foreach (string item in UsingList)
            {
                pNamespace.Imports.Add(new CodeNamespaceImport(item));
            }

            //Create compile unit
            CodeCompileUnit pUnit = new CodeCompileUnit();

            pUnit.Namespaces.Add(pNamespace);

            //Make compilation parameters
            CompilerParameters pParams =
                new CompilerParameters(ImportList.ToArray());

            pParams.GenerateInMemory = true;
            //Compile
            var             provider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults pResults = provider.CompileAssemblyFromDom(pParams, pUnit);

            if (pResults.Errors != null && pResults.Errors.Count > 0)
            {
                foreach (CompilerError pError in pResults.Errors)
                {
                    MessageBox.Show(pError.ToString());
                }
            }
            else
            {
                var result = (dynamic)pResults.CompiledAssembly.CreateInstance("CodeTextExecTest.MyTestClass");

                result.TestFunction("23939889");
            }
        }
Exemple #26
0
        /// <summary<
        /// 构造函数
        /// </summary<
        /// <param name="url"></param>
        public WebServiceAgent(string url, string NameSpace)
        {
            //判断文件存储路径是否存在
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            if (url.ToLower().IndexOf("?wsdl") == -1)
            {
                url = url + "?wsdl";
            }
            XmlTextReader reader = new XmlTextReader(url);

            CODE_NAMESPACE = NameSpace;
            //创建和格式化 WSDL 文档
            ServiceDescription sd = ServiceDescription.Read(reader);

            //创建客户端代理代理类
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, null, null);

            //使用 CodeDom 编译客户端代理类
            CodeNamespace   cn  = new CodeNamespace(CODE_NAMESPACE);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);

            Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters parameter            = new CompilerParameters();

            parameter.GenerateExecutable = false;
            parameter.OutputAssembly     = Path.Combine(dirPath, NameSpace + ".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");

            CompilerResults cr = icc.CompileAssemblyFromDom(parameter, 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());
            }

            agentType = cr.CompiledAssembly.GetTypes()[0];
            agent     = Activator.CreateInstance(agentType);
            //读取文件字节
            FileStream fileStream = agentType.Assembly.GetFiles()[0];

            using (BinaryReader br = new BinaryReader(fileStream))
            {
                fileByte = br.ReadBytes((int)fileStream.Length);
                fileStream.Dispose();
            }

            //TextWriter writer = File.CreateText("F:\\MyTest.cs");
            //icc.GenerateCodeFromCompileUnit(ccu, writer, null);
            //writer.Flush();
            //writer.Close();
        }
Exemple #27
0
        /// <summary>
        /// Creates a new Service Inspector from a given Uri of a WSDL
        /// </summary>
        /// <param name="serviceLocation">The location of the services WSDL file</param>
        public ServiceInspector(Uri serviceLocation)
        {
            if (serviceLocation.Query == string.Empty)
            {
                UriBuilder uriB = new UriBuilder(serviceLocation);

                uriB.Query = "WSDL";

                serviceLocation = uriB.Uri;
            }

            _serviceLocation = serviceLocation;

            WebRequest wsdlWebRequest    = WebRequest.Create(serviceLocation);
            Stream     wsdlRequestStream = wsdlWebRequest.GetResponse().GetResponseStream();

            //Get the ServiceDescription from the WSDL file
            ServiceDescription sd     = ServiceDescription.Read(wsdlRequestStream);
            string             sdName = sd.Services[0].Name;

            ServiceDescriptionImporter sdImport = new ServiceDescriptionImporter();

            sdImport.AddServiceDescription(sd, String.Empty, String.Empty);
            sdImport.ProtocolName          = "Soap";
            sdImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

            CodeNamespace   codeNameSpace   = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(codeNameSpace);

            ServiceDescriptionImportWarnings warnings = sdImport.Import(codeNameSpace, codeCompileUnit);

            if (warnings == 0)
            {
                StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();

                prov.GenerateCodeFromNamespace(codeNameSpace, stringWriter, new CodeGeneratorOptions());

                //Compile the assembly
                string[] assemblyReferences = new string[2] {
                    "System.Web.Services.dll", "System.Xml.dll"
                };
                CompilerParameters param = new CompilerParameters(assemblyReferences);

                param.GenerateExecutable    = false;
                param.GenerateInMemory      = true;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel          = 4;

                CompilerResults results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);

                Assembly assembly = results.CompiledAssembly;
                _service = assembly.GetType(sdName);

                _methodInfo.Clear();

                foreach (MethodInfo mi in _service.GetMethods())
                {
                    if (mi.Name == "Discover")
                    {
                        break;
                    }

                    _methodInfo.Add(mi);
                }
            }
        }
Exemple #28
0
        private static Type BuildTypeCodeDom(Type baseInterface, string className, string fieldsPrefix, params Type[] types)
        {
            var           compileUnit     = new CodeCompileUnit();
            CodeNamespace globalNamespace = new CodeNamespace();

            globalNamespace.Imports.Add(new CodeNamespaceImport("System"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Text"));

            var classNamespace = new CodeNamespace("STSdb4.Data");

            var generatedClass = new CodeTypeDeclaration(className);

            generatedClass.IsClass    = true;
            generatedClass.Attributes = MemberAttributes.Public;

            for (int i = 0; i < types.Length; i++)
            {
                generatedClass.TypeParameters.Add(new CodeTypeParameter("T" + fieldsPrefix + i));
            }

            if (baseInterface != null)
            {
                generatedClass.BaseTypes.Add(baseInterface);
            }

            var serializableAttribute = new CodeTypeReference(typeof(System.SerializableAttribute));

            generatedClass.CustomAttributes.Add(new CodeAttributeDeclaration(serializableAttribute));

            classNamespace.Types.Add(generatedClass);

            compileUnit.Namespaces.Add(globalNamespace);
            compileUnit.Namespaces.Add(classNamespace);

            CodeMemberField[] fields = new CodeMemberField[types.Length];

            for (int i = 0; i < fields.Length; i++)
            {
                fields[i]            = new CodeMemberField("T" + fieldsPrefix + i, fieldsPrefix + i);
                fields[i].Attributes = MemberAttributes.Public;
                generatedClass.Members.Add(fields[i]);
            }

            CodeConstructor defaultConstructor = new CodeConstructor();

            defaultConstructor.Attributes = MemberAttributes.Public;

            generatedClass.Members.Add(defaultConstructor);

            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;

            for (int i = 0; i < types.Length; i++)
            {
                CodeTypeReference type = new CodeTypeReference("T" + fieldsPrefix + i);
                constructor.Parameters.Add(new CodeParameterDeclarationExpression(type, fieldsPrefix.ToLower() + i));
            }

            for (int i = 0; i < types.Length; i++)
            {
                CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldsPrefix + i);
                constructor.Statements.Add(new CodeAssignStatement(left, new CodeArgumentReferenceExpression(fieldsPrefix.ToLower() + i)));
            }

            generatedClass.Members.Add(constructor);

            string stsdbAssemblyName = Assembly.GetExecutingAssembly().Location;

            string[] assemblies = { "System.dll", "mscorlib.dll", stsdbAssemblyName };

            CompilerParameters parameters = new CompilerParameters(assemblies);

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

            parameters = new CompilerParameters(assemblies);

            parameters.GenerateExecutable      = false;
            parameters.GenerateInMemory        = true;
            parameters.IncludeDebugInformation = true;
            parameters.CompilerOptions         = "/optimize";

            CompilerResults compilerResults = runTimeProvider.CompileAssemblyFromDom(parameters, compileUnit);
            var             generatedType   = compilerResults.CompiledAssembly.GetTypes()[0];

            return(generatedType.MakeGenericType(types));
        }
        public static Type CreateType(int classId, string name, Type t)
        {
            Type retType = null;

            if (_dynamicTypes == null)
            {
                _dynamicTypes = new Dictionary <int, Type>();
            }
            if (_dynamicTypes.TryGetValue(classId, out retType))
            {
                if (retType.Name != name)
                {
                    _dynamicTypes.Remove(classId);
                }
                else
                {
                    return(retType);
                }
            }
            string nsName = "LimnorStudioDesigner";
            // Create a code compile unit and a namespace
            CodeCompileUnit ccu = new CodeCompileUnit();
            CodeNamespace   ns  = new CodeNamespace(nsName);

            //
            // Add some imports statements to the namespace
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("LimnorDesigner"));
            //
            // Add the namespace to the code compile unit
            ccu.Namespaces.Add(ns);
            //
            //it can be sure that name is unique because it is a component name
            CodeTypeDeclaration ctd = new CodeTypeDeclaration(name);

            ctd.BaseTypes.Add(typeof(ClassHolder));
            ns.Types.Add(ctd);
            //
            ctd.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(CustomTypeAttribute)),
                                                                  new CodeAttributeArgument(new CodePrimitiveExpression(classId))
                                                                  //,new CodeAttributeArgument(new CodeTypeReferenceExpression(t))
                                                                  )
                                     );
            //
            Dictionary <string, Assembly> _refLocations = new Dictionary <string, Assembly>();

            DesignUtil.FindReferenceLocations(_refLocations, typeof(ClassHolder).Assembly);
            //
            //compile it
            CodeDomProvider    provider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp       = new CompilerParameters(new string[] {
                //"System.dll"
                //,typeof(ClassHolder).Assembly.Location
                //,typeof(VPL.VPLUtil).Assembly.Location
            });
            Assembly aly = Assembly.GetAssembly(typeof(System.ComponentModel.Component));

            if (!_refLocations.ContainsKey(aly.Location.ToLower()))
            {
                cp.ReferencedAssemblies.Add(aly.Location);
            }
            foreach (string loc in _refLocations.Keys)
            {
                cp.ReferencedAssemblies.Add(loc);
            }
            cp.GenerateInMemory   = true;
            cp.OutputAssembly     = "LimnorStudioAutoGenerated.dll";
            cp.GenerateExecutable = false;
            cp.CompilerOptions    = "/t:library";
            CompilerResults results = provider.CompileAssemblyFromDom(cp, ccu);

            if (results.Errors == null || results.Errors.Count == 0)
            {
                Type[] tps = results.CompiledAssembly.GetExportedTypes();
                for (int i = 0; i < tps.Length; i++)
                {
                    if (tps[i].Name == name)
                    {
                        retType = tps[i];
                        _dynamicTypes.Add(classId, retType);
                        break;
                    }
                }
            }
            else
            {
                StringCollection sc = new StringCollection();
                foreach (CompilerError e in results.Errors)
                {
                    sc.Add(e.ErrorText);
                }
                FormMsgList.ShowStrings(sc);
            }
            return(retType);
        }
Exemple #30
0
        public static Assembly CompileInMemory(CodeCompileUnit[] codeCompileUnits, string[] assemblyNames)
        {
            // TODO: better way?
            var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            var compileOptions = new CompilerParameters();
            compileOptions.GenerateInMemory = true;

            compileOptions.ReferencedAssemblies.AddRange(assemblyNames);
            CompilerResults results = codeProvider.CompileAssemblyFromDom(compileOptions, codeCompileUnits);
            if (results.Errors.Count > 0)
            {
                List<string> errors = new List<string>();
                foreach (CompilerError error in results.Errors)
                {
                    errors.Add(string.Format("{0} Line {1} Column {2}", error.ErrorText, error.Line, error.Column));
                }

                StringBuilder sb = new StringBuilder();
                foreach (string error in errors)
                {
                    sb.AppendFormat("\n\n{0}", error);
                }
                string errorText = sb.ToString();

                throw CodeCompilerException.NewFormat(
                    results.Errors,
                    codeCompileUnits,
                    codeProvider,
                    "Errors in compiling CodeCompileUnits: {0}",
                    errorText
                    );
            }

            return results.CompiledAssembly;
        }
Exemple #31
0
        /// <summary>
        /// hook event to a generic event handler
        /// </summary>
        /// <param name="ep">event sender</param>
        /// <param name="gh">the generic event handler</param>
        /// <returns></returns>
        static public CompilerErrorCollection LinkEvent(IEventPointer ep, fnGenericHandler gh)
        {
            EventLinkerCollection ec = null;

            if (eventLinks.ContainsKey(ep.Info.EventHandlerType))
            {
                ec = eventLinks[ep.Info.EventHandlerType];
            }
            else
            {
                string nsName = "DynamicEventLinker";
                // Create a code compile unit and a namespace
                CodeCompileUnit ccu = new CodeCompileUnit();
                CodeNamespace   ns  = new CodeNamespace(nsName);

                // Add some imports statements to the namespace
                ns.Imports.Add(new CodeNamespaceImport("System"));
                ns.Imports.Add(new CodeNamespaceImport("DynamicEventLinker"));
                //ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
                //ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));

                // Add the namespace to the code compile unit
                ccu.Namespaces.Add(ns);
                //
                //Make class name unique
                string className = "DLink1";
                int    n         = 1;
                while (true)
                {
                    bool bFound = false;
                    foreach (KeyValuePair <Type, EventLinkerCollection> kv in eventLinks)
                    {
                        if (kv.Value.DynamicClassType.Name == className)
                        {
                            bFound = true;
                            n++;
                            className = "DLink" + n.ToString();
                        }
                    }
                    if (!bFound)
                    {
                        break;
                    }
                }
                CodeTypeDeclaration ctd = new CodeTypeDeclaration(className);
                ctd.BaseTypes.Add(typeof(object));
                ns.Types.Add(ctd);
                //
                CodeConstructor constructor = new CodeConstructor();
                constructor.Attributes = MemberAttributes.Public;
                ctd.Members.Add(constructor);
                constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IEventPointer), "eventId"));
                constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(fnGenericHandler), "handler"));
                ctd.Members.Add(new CodeMemberField(typeof(IEventPointer), "_eventId"));
                ctd.Members.Add(new CodeMemberField(typeof(fnGenericHandler), "_handler"));
                constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_eventId"),
                                                                   new CodeVariableReferenceExpression("eventId")));
                constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_handler"),
                                                                   new CodeVariableReferenceExpression("handler")));
                //
                //payload
                CodeMemberMethod method = new CodeMemberMethod();
                MethodInfo       mif    = ep.Info.EventHandlerType.GetMethod("Invoke");
                ParameterInfo[]  pifs   = mif.GetParameters();
                method.Name       = "HookEvent";
                method.Attributes = MemberAttributes.Public;
                method.ReturnType = new CodeTypeReference(typeof(void));
                for (int i = 0; i < pifs.Length; i++)
                {
                    method.Parameters.Add(new CodeParameterDeclarationExpression(pifs[i].ParameterType, pifs[i].Name));
                }
                //call _handler passing eventId and parameters to it
                //create parameter array
                CodeExpression[] paramArray = new CodeExpression[pifs.Length];
                for (int i = 0; i < pifs.Length; i++)
                {
                    paramArray[i] = new CodeVariableReferenceExpression(pifs[i].Name);
                }
                //make the array variable name unique
                string arrayName = "paramArray";
                n = 1;
                while (true)
                {
                    bool bFound = false;
                    for (int i = 0; i < pifs.Length; i++)
                    {
                        if (pifs[i].Name == arrayName)
                        {
                            bFound = true;
                            n++;
                            arrayName = "paramArray" + n.ToString();
                        }
                    }
                    if (!bFound)
                    {
                        break;
                    }
                }

                method.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), arrayName,
                                                                           new CodeArrayCreateExpression(typeof(object), paramArray)));
                //call _handler
                method.Statements.Add(new CodeDelegateInvokeExpression(new CodeFieldReferenceExpression(
                                                                           new CodeThisReferenceExpression(), "_handler"), new CodeExpression[] {
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_eventId"),
                    new CodeVariableReferenceExpression(arrayName)
                }));
                //
                ctd.Members.Add(method);
                //method returns a delegate for the event-specific handler to be added to the event's handler
                method            = new CodeMemberMethod();
                method.Name       = "GetHookEvent";
                method.Attributes = MemberAttributes.Public;
                method.ReturnType = new CodeTypeReference(ep.Info.EventHandlerType);
                method.Statements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(
                                                                        ep.Info.EventHandlerType, new CodeExpression[] {
                    new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "HookEvent")
                }
                                                                        )));
                ctd.Members.Add(method);
                //compile it
                CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                //ICodeCompiler compiler = provider.CreateGenerator() as ICodeCompiler;
                string linker = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DynamicEventLinker.dll");
                if (!System.IO.File.Exists(linker))
                {
                    CompilerErrorCollection errs = new CompilerErrorCollection();
                    errs.Add(new CompilerError("DynamicLinker", 3, 3, "3", "Linker not found:" + linker));
                    return(errs);
                }
                CompilerParameters cp = new CompilerParameters(new string[] {
                    "System.dll", linker /*"System.Windows.Forms.dll", "System.Drawing.dll"*/
                });
                cp.GenerateInMemory = true;
                cp.OutputAssembly   = "AutoGenerated";
                CompilerResults results = provider.CompileAssemblyFromDom(cp, ccu);
                if (results.Errors == null || results.Errors.Count == 0)
                {
                    Type[] tps = results.CompiledAssembly.GetExportedTypes();
                    for (int i = 0; i < tps.Length; i++)
                    {
                        if (tps[i].Name == className)
                        {
                            ec = new EventLinkerCollection(tps[i]);
                            eventLinks.Add(ep.Info.EventHandlerType, ec);
                            break;
                        }
                    }
                }
                else
                {
                    return(results.Errors);
                }
            }
            if (ec != null)
            {
                try
                {
                    object     ev = Activator.CreateInstance(ec.DynamicClassType, new object[] { ep, gh });
                    MethodInfo mi = ec.DynamicClassType.GetMethod("GetHookEvent");
                    Delegate   eh = (Delegate)mi.Invoke(ev, new object[] { });
                    ep.Info.AddEventHandler(ep.ObjectInstance, eh);
                    if (ec.ContainsKey(ep))
                    {
                        ec[ep] = ev;
                    }
                    else
                    {
                        ec.Add(ep, ev);
                    }
                }
                catch (Exception er)
                {
                    CompilerErrorCollection errs = new CompilerErrorCollection();
                    errs.Add(new CompilerError("DynamicLinker", 2, 2, "2", string.Format("{0}. {1}", er.Message, er.StackTrace)));
                    return(errs);
                }
            }
            else
            {
                CompilerErrorCollection errs = new CompilerErrorCollection();
                errs.Add(new CompilerError("DynamicLinker", 1, 1, "1", "Dynamic type not found"));
                return(errs);
            }
            return(null);
        }
Exemple #32
0
        /// <summary>
        /// 取得webservice instance
        /// </summary>
        /// <param name="url">url+?wsdl</param>
        /// <param name="assemblyReferences"></param>
        /// <param name="output"></param>
        /// <returns></returns>
        public static bool GetWebServiceInstance(string url, string[] assemblyReferences, out LkReflectModel output, string userName = "", string password = "")
        {
            //http://www.codeproject.com/Articles/18950/Dynamic-Discovery-and-Invocation-of-Web-Services
            //https://dotblogs.com.tw/jimmyyu/archive/2009/04/22/8139.aspx

            output = new LkReflectModel();
            if (assemblyReferences == null)
            {
                assemblyReferences = new string[3] {
                    "System.Web.Services.dll", "System.Xml.dll", "System.Data.dll"
                };
            }
            bool result = false;

            try
            {
                WebRequest webRequest = WebRequest.Create(url);

                //有要權限的話要加下面
                //webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    webRequest.Credentials     = new NetworkCredential(userName, password);
                    webRequest.PreAuthenticate = true;
                }
                Stream requestStream = webRequest.GetResponse().GetResponseStream();
                // Get a WSDL file describing a service
                //ServiceDescription类提供一种方法,以创建和格式化用于描述 XML Web services 的有效的 Web 服务描述语言 (WSDL) 文档文件,该文件是完整的,具有适当的命名空间、元素和特性。 无法继承此类。
                //ServiceDescription.Read 方法 (Stream) 通过直接从 Stream实例加载 XML 来初始化ServiceDescription类的实例。
                ServiceDescription sd     = ServiceDescription.Read(requestStream);
                string             sdName = sd.Services[0].Name;

                // Initialize a service description servImport
                //ServiceDescriptionImporter 类 公开一种为 XML Web services 生成客户端代理类的方法。
                //ServiceDescriptionImporter.AddServiceDescription 方法 将指定的ServiceDescription添加到要导入的ServiceDescriptions值的集合中。
                ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
                servImport.AddServiceDescription(sd, String.Empty, String.Empty);
                servImport.ProtocolName          = "Soap";
                servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

                //CodeNamespace表示命名空间声明。
                CodeNamespace nameSpace = new CodeNamespace();
                //CodeCompileUnit会提供一个CodeDOM程式圆形的容器,CodeCompileUnit含有一个集合,可以储存含有CodeDOM原始程式码原形,专案参考的组件集合以及专案组件属性集合的CodeNamespace物件。
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(nameSpace);
                // Set Warnings
                ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

                if (warnings == 0)
                {
                    StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                    //CSharpCodeProvider类提供存取C#程式码产生器和程式码编译器的执行个体。
                    Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                    // 取得C#程式码编译器的执行个体
                    prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                    // Compile the assembly with the appropriate references
                    // 创建编译器的参数实例
                    CompilerParameters param = new CompilerParameters(assemblyReferences);
                    param.GenerateExecutable    = false;
                    param.GenerateInMemory      = true;
                    param.TreatWarningsAsErrors = false;
                    param.WarningLevel          = 4;

                    // CompilerResults表示从编译器返回的编译结果。使用指定的编译器设定,根据CodeCompileUnit物件之指定阵列所包含的System.CodeDom树状结构,编译一个组件。
                    CompilerResults results = new CompilerResults(new TempFileCollection());
                    // Compile
                    results = prov.CompileAssemblyFromDom(param, codeCompileUnit);

                    if (true == results.Errors.HasErrors)
                    {
                        System.Text.StringBuilder tStr = new System.Text.StringBuilder();
                        foreach (System.CodeDom.Compiler.CompilerError tComError in results.Errors)
                        {
                            tStr.Append(tComError.ToString());
                            tStr.Append(System.Environment.NewLine);
                        }
                        throw new Exception(tStr.ToString());
                    }

                    output.Assembly      = results.CompiledAssembly;
                    output.Class         = output.Assembly.GetType(sdName);
                    output.ClassInstance = Activator.CreateInstance(output.Class);
                    result = true;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
Exemple #33
0
        private void DynamicInvocation()
        {
            try
            {
                messageTextBox.Text += "Generating WSDL \r\n";
                progressBar1.PerformStep();

                Uri uri = new Uri(textBox1.Text);

                messageTextBox.Text += "Generating WSDL \r\n";
                progressBar1.PerformStep();

                WebRequest       webRequest    = WebRequest.Create(uri);
                System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
                // Get a WSDL file describing a service
                ServiceDescription sd     = ServiceDescription.Read(requestStream);
                string             sdName = sd.Services[0].Name;
                // Add in tree view
                treeWsdl.Nodes.Add(sdName);

                messageTextBox.Text += "Generating Proxy \r\n";
                progressBar1.PerformStep();

                // Initialize a service description servImport
                ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
                servImport.AddServiceDescription(sd, String.Empty, String.Empty);
                servImport.ProtocolName          = "Soap";
                servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

                messageTextBox.Text += "Generating assembly  \r\n";
                progressBar1.PerformStep();

                CodeNamespace   nameSpace       = new CodeNamespace();
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(nameSpace);
                // Set Warnings
                ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

                if (warnings == 0)
                {
                    StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
                    Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                    prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

                    messageTextBox.Text += "Compiling assembly \r\n";
                    progressBar1.PerformStep();

                    // Compile the assembly with the appropriate references
                    string[] assemblyReferences = new string[2] {
                        "System.Web.Services.dll", "System.Xml.dll"
                    };
                    CompilerParameters param = new CompilerParameters(assemblyReferences);
                    param.GenerateExecutable    = false;
                    param.GenerateInMemory      = true;
                    param.TreatWarningsAsErrors = false;
                    param.WarningLevel          = 4;

                    CompilerResults results = new CompilerResults(new TempFileCollection());
                    results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                    Assembly assembly = results.CompiledAssembly;
                    service = assembly.GetType(sdName);

                    messageTextBox.Text += "Get Methods of Wsdl \r\n";
                    progressBar1.PerformStep();

                    methodInfo = service.GetMethods();
                    foreach (MethodInfo t in methodInfo)
                    {
                        if (t.Name == "Discover")
                        {
                            break;
                        }


                        treeWsdl.Nodes[0].Nodes.Add(t.Name);
                    }

                    treeWsdl.Nodes[0].Expand();

                    messageTextBox.Text += "Now ready to invoke \r\n ";
                    progressBar1.PerformStep();
                    this.tabControl1.SelectedTab = this.tabPage1;
                }
                else
                {
                    messageTextBox.Text += warnings;
                }
            }
            catch (Exception ex)
            {
                messageTextBox.Text += "\r\n" + ex.Message + "\r\n\r\n" + ex.ToString();;
                progressBar1.Value   = 70;
            }
        }
Exemple #34
0
        public Type GetProxyTypeForStateInterface()
        {
            if (_proxyTypeCache == null)
            {
                List <Type> typesRequired = new List <Type>();
                typesRequired.Add(_interfaceType);

                // Create a code compile unit and a namespace
                CodeCompileUnit ccu = new CodeCompileUnit();
                CodeNamespace   ns  = new CodeNamespace("Esmf.StateTypes");

                // Add some imports statements to the namespace
                ns.Imports.Add(new CodeNamespaceImport("System"));
                // ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));

                // Add the namespace to the code compile unit
                ccu.Namespaces.Add(ns);

                string implementationTypeName = _interfaceName.StartsWith("I", StringComparison.OrdinalIgnoreCase) ? _interfaceName.Substring(1) : String.Format("{0}Implementation", _interfaceName);
                CodeTypeDeclaration ctd       = new CodeTypeDeclaration(implementationTypeName);
                ctd.BaseTypes.Add(_interfaceType);
                ctd.BaseTypes.Add(typeof(IStateObjectConnections));


                ns.Types.Add(ctd);

                foreach (StateFieldStructure field in _fields)
                {
                    if (!typesRequired.Contains(field.Type))
                    {
                        typesRequired.Add(field.Type);
                    }

                    if (field.Dimensions.Count == 0)
                    {
                        CodeTypeReference tt = new CodeTypeReference(field.Type);

                        CodeTypeReference ttGetter = new CodeTypeReference(typeof(NonDimensionalFieldGetter <>));
                        ttGetter.TypeArguments.Add(tt);
                        string          _fieldGetter   = String.Format("_{0}FieldGetter", field.Name);
                        CodeMemberField newGetterField = new CodeMemberField(ttGetter, _fieldGetter);
                        ctd.Members.Add(newGetterField);

                        CodeMemberProperty p = new CodeMemberProperty();
                        p.Name        = String.Format("{0}.{1}", _interfaceType, field.Name);
                        p.Type        = tt;
                        p.Attributes -= MemberAttributes.Private;
                        CodeStatementCollection getStatements = p.GetStatements;

                        getStatements.Add(
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    new CodeFieldReferenceExpression(
                                        new CodeThisReferenceExpression(),
                                        _fieldGetter),
                                    CodeBinaryOperatorType.IdentityInequality,
                                    new CodePrimitiveExpression(null)),
                                new CodeStatement[] { new CodeMethodReturnStatement(new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), _fieldGetter))) },
                                new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(InvalidOperationException)))) }));

                        if (field.CanWrite)
                        {
                            CodeTypeReference ttSetter = new CodeTypeReference(typeof(NonDimensionalFieldSetter <>));
                            ttSetter.TypeArguments.Add(tt);
                            string          _fieldSetter   = String.Format("_{0}FieldSetter", field.Name);
                            CodeMemberField newSetterField = new CodeMemberField(ttSetter, _fieldSetter);
                            ctd.Members.Add(newSetterField);

                            CodeStatementCollection setStatements = p.SetStatements;

                            setStatements.Add(
                                new CodeConditionStatement(
                                    new CodeBinaryOperatorExpression(
                                        new CodeFieldReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                            _fieldSetter),
                                        CodeBinaryOperatorType.IdentityInequality,
                                        new CodePrimitiveExpression(null)),
                                    new CodeStatement[] { new CodeExpressionStatement(new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), _fieldSetter), new CodeExpression[] { new CodePropertySetValueReferenceExpression() })) },
                                    new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(InvalidOperationException)))) }));
                        }

                        ctd.Members.Add(p);
                    }
                    else if (field.Dimensions.Count > 0)
                    {
                        CodeTypeReference tt;
                        if (field.CanWrite)
                        {
                            if (field.Dimensions.Count == 1)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IVariable1Dimensional <,>));
                            }
                            else if (field.Dimensions.Count == 2)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IVariable2Dimensional <, ,>));
                            }
                            else
                            {
                                throw new InvalidOperationException("Can't have parameters with more than 2 dimensions");
                            }
                        }
                        else
                        {
                            if (field.Dimensions.Count == 1)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IParameter1Dimensional <,>));
                            }
                            else if (field.Dimensions.Count == 2)
                            {
                                tt = new CodeTypeReference(typeof(Esmf.IParameter2Dimensional <, ,>));
                            }
                            else
                            {
                                throw new InvalidOperationException("Can't have fields with more than 2 dimensions");
                            }
                        }

                        foreach (StateFieldDimensionStructure sfds in field.Dimensions)
                        {
                            tt.TypeArguments.Add(sfds.Type);

                            if (!typesRequired.Contains(sfds.Type))
                            {
                                typesRequired.Add(sfds.Type);
                            }
                        }
                        tt.TypeArguments.Add(field.Type);

                        string          fieldName = String.Format("_{0}Field", field.Name);
                        CodeMemberField newField  = new CodeMemberField(tt, fieldName);
                        ctd.Members.Add(newField);

                        CodeMemberProperty p = new CodeMemberProperty();
                        p.Name        = String.Format("{0}.{1}", _interfaceType, field.Name);
                        p.Type        = tt;
                        p.Attributes -= MemberAttributes.Private;
                        CodeStatementCollection statements = p.GetStatements;

                        statements.Add(
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    new CodeFieldReferenceExpression(
                                        new CodeThisReferenceExpression(),
                                        fieldName),
                                    CodeBinaryOperatorType.IdentityInequality,
                                    new CodePrimitiveExpression(null)),
                                new CodeStatement[] { new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName)) },
                                new CodeStatement[] { new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(InvalidOperationException)))) }));
                        ctd.Members.Add(p);
                    }
                }


                GenerateCodeForIStateObjectConnection(ctd);

                CodeDomProvider    provider = new Microsoft.CSharp.CSharpCodeProvider();
                CompilerParameters cp       = new CompilerParameters();
                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add(typeof(IParameter1Dimensional <,>).Module.FullyQualifiedName);

                List <string> modules = new List <string>();
                foreach (Type t in typesRequired)
                {
                    if (!modules.Contains(t.Module.FullyQualifiedName))
                    {
                        modules.Add(t.Module.FullyQualifiedName);
                    }
                }

                foreach (string s in modules)
                {
                    cp.ReferencedAssemblies.Add(s);
                }


                cp.GenerateInMemory = true;
                string assemblyDirectory = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Temp");
                if (!Directory.Exists(assemblyDirectory))
                {
                    Directory.CreateDirectory(assemblyDirectory);
                }
                cp.OutputAssembly = Path.Combine(assemblyDirectory, string.Format("AutoGenerated{0}.dll", Guid.NewGuid()));
                CompilerResults results = provider.CompileAssemblyFromDom(cp, ccu);
                if (results.Errors.HasErrors)
                {
                    foreach (CompilerError err in results.Errors)
                    {
                        Console.WriteLine();
                        Console.WriteLine(err);
                    }
                }

                //CodeDomProvider provider2 = new Microsoft.CSharp.CSharpCodeProvider();
                //using (System.IO.TextWriter output = System.IO.File.CreateText(@"C:\Users\davidanthoff\Documents\Visual Studio 2005\Projects\test.cs"))
                //{
                //    provider2.GenerateCodeFromCompileUnit(ccu, output, new CodeGeneratorOptions());
                //}

                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

                _proxyTypeCache = results.CompiledAssembly.GetType("Esmf.StateTypes." + implementationTypeName);

                AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);

                return(_proxyTypeCache);
            }
            else
            {
                return(_proxyTypeCache);
            }
        }