public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceProxy.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
/// <summary> /// get an Assembly according to wsdl path. /// </summary> /// <param name="wsdl">wsdl path</param> /// <param name="nameSpace">namespace</param> /// <returns>return Assembly</returns> public static Assembly GetWebServiceAssembly(string wsdl, string nameSpace) { try { System.Net.WebClient webClient = new System.Net.WebClient(); System.IO.Stream webStream = webClient.OpenRead(wsdl); ServiceDescription serviceDescription = ServiceDescription.Read(webStream); ServiceDescriptionImporter serviceDescroptImporter = new ServiceDescriptionImporter(); serviceDescroptImporter.AddServiceDescription(serviceDescription, "", ""); System.CodeDom.CodeNamespace codeNameSpace = new System.CodeDom.CodeNamespace(nameSpace); System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNameSpace); serviceDescroptImporter.Import(codeNameSpace, codeCompileUnit); System.CodeDom.Compiler.CodeDomProvider codeDom = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters codeParameters = new System.CodeDom.Compiler.CompilerParameters(); codeParameters.GenerateExecutable = false; codeParameters.GenerateInMemory = true; codeParameters.ReferencedAssemblies.Add("System.dll"); codeParameters.ReferencedAssemblies.Add("System.XML.dll"); codeParameters.ReferencedAssemblies.Add("System.Web.Services.dll"); codeParameters.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults compilerResults = codeDom.CompileAssemblyFromDom(codeParameters, codeCompileUnit); return compilerResults.CompiledAssembly; } catch (Exception ex) { throw ex; } }
[MonoTODO] // where to use Verbose and Extensions in options? public static StringCollection GenerateWebReferences ( WebReferenceCollection webReferences, CodeDomProvider codeGenerator, CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { StringCollection allWarnings = new StringCollection (); ImportContext context = new ImportContext (new CodeIdentifiers(), true); foreach (WebReference reference in webReferences) { ServiceDescriptionImporter importer = new ServiceDescriptionImporter (); if (codeGenerator != null) importer.CodeGenerator = codeGenerator; importer.CodeGenerationOptions = options.CodeGenerationOptions; importer.Context = context; importer.Style = options.Style; importer.ProtocolName = reference.ProtocolName; importer.AddReference (reference); reference.Warnings = importer.Import (reference.ProxyCode, codeCompileUnit); reference.SetValidationWarnings (context.Warnings); foreach (string s in context.Warnings) allWarnings.Add (s); context.Warnings.Clear (); } return allWarnings; }
public object Invoke(string url, string methodName, string className = "", params object[] args) { if (className == null || className == "") { className = GetClassName(url); } string @namespace = "ServiceBase.WebService.DynamicWebLoad." + ProcessUrl(url); string cacheName = string.Format("{0}_{1}", @namespace, className); Assembly assembly = null; if (HttpContext.Current.Cache[cacheName] != null) { assembly = HttpContext.Current.Cache[cacheName] as Assembly; } else { //获取服务描述语言(WSDL) WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译器的参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 assembly = cr.CompiledAssembly; HttpContext.Current.Cache[cacheName] = assembly; } 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); }
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; } } }
/// <summary> 根据参数执行WebService </summary> public static object InvokeWebService(string url, string classname, string methodname, object[] args) { try { string _namespace = "WebService"; if (string.IsNullOrEmpty(classname)) { classname = GetClassName(url); } //获取服务描述语言(WSDL) Net.WebClient wc = new Net.WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); //【1】 Web.Services.Description.ServiceDescription sd = Web.Services.Description.ServiceDescription.Read(stream); //【2】 Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】 sdi.AddServiceDescription(sd, "", ""); CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace); //【4】 //生成客户端代理类代码 CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit(); //【5】 ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】 CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); //ICodeCompiler icc = csc.CreateCompiler();//【7】 //设定编译器的参数 CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】 cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(_namespace + "." + classname, true, true); object bj = Activator.CreateInstance(t); //【10】 System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】 return(mi.Invoke(bj, args)); } catch (System.Exception ex) { Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace); //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test"); return(null); } }
CodeNamespace GenerateCodeFromWsdl (ServiceDescription sd) { ServiceDescriptionImporter imp = new ServiceDescriptionImporter (); imp.AddServiceDescription (sd, null, null); CodeNamespace cns = new CodeNamespace (); imp.Import (cns, null); return cns; }
/// <summary> /// This is the workhorse method of the program. Given a web service type, /// it generates a proxy class for it, strips out any excess types, and then /// adds a few using statments to it. /// </summary> /// <param name="type">The web service type</param> /// <param name="uri">The URL for the service that will be set in the constructor</param> private bool Compile() { try { // These next two lines do the generate the WSDL based on the web service class ServiceDescriptionReflector reflector = new ServiceDescriptionReflector(); reflector.Reflect(m_type, m_uri); if (reflector.ServiceDescriptions.Count > 1) throw new Exception(string.Format("Don't know how to deal with multiple service descriptions in {0}", m_type)); // Now we take the WSDL service description and turn it into a proxy in CodeDOM form ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.AddServiceDescription(reflector.ServiceDescriptions[0], null, null); importer.Style = m_style; // Probably a good idea to make the namespace a command-line parameter, but hardcode it for now //CodeNamespace codeNamespace = new CodeNamespace("Integic.ePower.Psd.WebServices.Common.Proxies"); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(CodeNamespace); ServiceDescriptionImportWarnings warnings = importer.Import(CodeNamespace, codeCompileUnit); // TODO: explicitly handle all of the warnings generated by the ServiceImporter if (warnings != 0) { Trace.TraceError("Warnings: {1}", warnings); string errorMessage; switch (warnings) { case ServiceDescriptionImportWarnings.NoMethodsGenerated: errorMessage = string.Format("Error: Web service at {0} does not contain any web methods", m_type.FullName); throw new ApplicationException(errorMessage); case ServiceDescriptionImportWarnings.NoCodeGenerated: errorMessage = string.Format("Error: No code was generated for web service at {0}", m_type.FullName); throw new ApplicationException(errorMessage); default: errorMessage = string.Format("Error: Unhandled error while generating code for web service {0} : {1}", m_type.FullName, warnings.ToString()); throw new ApplicationException(errorMessage); } } if (!GenerateCode()) return false; } catch (Exception ex) { Errors.Add(new CompilerError(string.Empty, 0, 0, string.Empty, ex.Message)); Trace.TraceError(ex.ToString()); return false; } return true; }
/// <summary> /// 实例化WebServices /// </summary> /// <param name="url">WebServices地址</param> /// <param name="methodname">调用的方法</param> /// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param> public static object InvokeWebService(string url, string methodname, object[] args) { //这里的namespace是需引用的webservices的命名空间,我没有改过,也可以使用。也可以加一个参数从外面传进来。 string @namespace = "client"; try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); string classname = sd.Services[0].Name; ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); //ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = 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); } catch(Exception ex) { return ex.Message; } }
private object InvokeWebservice(string url, string space, string classname, string methodname, object[] args) { try { System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(space); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(space + "." + classname, true, true); object obj = Activator.CreateInstance(t); //用来解决webservice上面有重载函数的问题 Type[] types = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { types[i] = args[i].GetType(); } System.Reflection.MethodInfo mi = t.GetMethod(methodname, types); if (null == mi) { return(null); } return(mi.Invoke(obj, args)); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public static object Invoke(string url, string className, string methodName, object[] parameters) { string compileNamespace = "Dynamic.To.Call.WebService"; if ((className == null) || (className == "")) { className = WebServiceHelper.GetClassName(url); } //Get wsdl information WebClient wc = new WebClient(); System.IO.Stream strm = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(strm); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(compileNamespace); //Generate client proxy class CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //Setting compile parameters CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.XML.dll"); compilerParams.ReferencedAssemblies.Add("System.Web.Services.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.dll"); //compile agentcy class CompilerResults cr = icc.CompileAssemblyFromDom(compilerParams, 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()); } //Build agent entity & call method System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(string.Concat(compileNamespace, ".", className), true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodName); if (parameters != null && parameters.Length > 0) return mi.Invoke(obj, parameters); else //Invoke(obj, BindingFlags.Default, new MyBinder(), new Object[] { (int)32, (int)32 }, CultureInfo.CurrentCulture);//ref to msdn return mi.Invoke(obj, BindingFlags.Default, null, null, null); }
public static object WebserviceInvoke(string p_strUrl, string p_strNameSpace, string p_strClassName, string p_strMethodName, object[] p_objArgs) { object oReturnValue = null; try { if (p_strNameSpace == "") { p_strNameSpace = "EnterpriseServerBase.WebService.DynamicWebCalling"; } if (p_strClassName == "") { p_strClassName = WebServiceHelper.GetWsClassName(p_strUrl); } System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(p_strUrl + "?wsdl"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(p_strNameSpace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(p_strNameSpace + "." + p_strClassName, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(p_strMethodName); oReturnValue = mi.Invoke(obj, p_objArgs); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } return(oReturnValue); }
public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, System.CodeDom.CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { if (codeCompileUnit != null) { codeCompileUnit.ReferencedAssemblies.Add("System.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll"); } Hashtable namespaces = new Hashtable(); Hashtable exportContext = new Hashtable(); foreach (WebReference reference in webReferences) { ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit); XmlSchemas schemas = new XmlSchemas(); ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection(); foreach (DictionaryEntry entry in reference.Documents) { AddDocument((string)entry.Key, entry.Value, schemas, descriptions, reference.ValidationWarnings); } importer.Schemas.Add(schemas); foreach (ServiceDescription description in descriptions) { importer.AddServiceDescription(description, reference.AppSettingUrlKey, reference.AppSettingBaseUrl); } importer.CodeGenerator = codeProvider; importer.ProtocolName = reference.ProtocolName; importer.Style = options.Style; importer.CodeGenerationOptions = options.CodeGenerationOptions; foreach (string str in options.SchemaImporterExtensions) { importer.Extensions.Add(Type.GetType(str, true)); } System.Xml.Serialization.ImportContext importContext = Context(reference.ProxyCode, namespaces, options.Verbose); reference.Warnings = importer.Import(reference.ProxyCode, importContext, exportContext, reference.ValidationWarnings); if (reference.ValidationWarnings.Count != 0) { reference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation; } } StringCollection strings = new StringCollection(); if (options.Verbose) { foreach (System.Xml.Serialization.ImportContext context2 in namespaces.Values) { foreach (string str2 in context2.Warnings) { strings.Add(str2); } } } return(strings); }
public static Type GetWsProxyType(string wsUrl, string classname) { string name = "ESBasic.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = GetWsClassName(wsUrl); } string key = wsUrl + "@" + classname; if (WSProxyTypeDictionary.ContainsKey(key)) { return WSProxyTypeDictionary[key]; } WebClient client = new WebClient(); ServiceDescription serviceDescription = ServiceDescription.Read(client.OpenRead(wsUrl + "?WSDL")); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.AddServiceDescription(serviceDescription, "", ""); CodeNamespace namespace2 = new CodeNamespace(name); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(namespace2); importer.Import(namespace2, codeCompileUnit); ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler(); CompilerParameters options = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.XML.dll"); options.ReferencedAssemblies.Add("System.Web.Services.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults results = compiler.CompileAssemblyFromDom(options, codeCompileUnit); if (results.Errors.HasErrors) { StringBuilder builder = new StringBuilder(); foreach (CompilerError error in results.Errors) { builder.Append(error.ToString()); builder.Append(Environment.NewLine); } throw new Exception(builder.ToString()); } Assembly compiledAssembly = results.CompiledAssembly; compiledAssembly.GetTypes(); Type type2 = compiledAssembly.GetType(name + "." + classname, true, true); lock (WSProxyTypeDictionary) { if (!WSProxyTypeDictionary.ContainsKey(key)) { WSProxyTypeDictionary.Add(key, type2); } } return type2; }
/// <summary> /// ��̬����WebService /// </summary> /// <param name="url">WebService��ַ</param> /// <param name="classname">����</param> /// <param name="methodname">������(ģ����)</param> /// <param name="args">�����б�</param> /// <returns>object</returns> public static object InvokeWebServiceNew(string url, string classname, string methodname, object[] args) { string @namespace = "ServiceBase.WebService.DynamicWebLoad"; if (classname == null || classname == "") { classname = CallWebServise.GetClassName(url); } //��ȡ������������(WSDL) WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //���ɿͻ��˴������ CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //�趨�������IJ��� CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //��������� CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (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); }
private static CodeCompileUnit BuildCodeCompileUnit(ServiceDescriptionImporter descriptionImporter) { var codeNamespace = new CodeNamespace(); var codeUnit = new CodeCompileUnit(); codeUnit.Namespaces.Add(codeNamespace); var importWarnings = descriptionImporter.Import(codeNamespace, codeUnit); if (importWarnings != 0) throw new Exception("Invalid WSDL"); return codeUnit; }
/// <summary> /// 通过反射完成WS调用 /// </summary> /// <param name="url">WSUrl</param> /// <param name="namespace">WS命名空间</param> /// <param name="classname">WS类名</class> /// <param name="methodname">WS方法名</class> /// <param name="args">传递给WS方法的参数</param> /// 示例:url="http://win01:86";serviceUrl = "/Api/SiteGroupFunc.asmx"; /// object s = InvokeWebSer(url + serviceUrl, "SiteGroup", "SiteGroupFunc", "GetSiteName", new object[] { }); /// <returns>执行结果</returns> public object InvokeWS(string url, string @namespace, string classname, string methodname, object[] args) { System.Net.WebClient wc = new System.Net.WebClient(); string URL = string.Empty; if ((url.Substring(url.Length - 5, 5) != null) && ((url.Substring(url.Length - 5, 5).ToLower() != "?wsdl"))) { URL = url + "?WSDL"; } else { URL = url; } System.IO.Stream stream = wc.OpenRead(URL); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return(mi.Invoke(obj, args)); }
/// <summary> /// 动态 WebService 构造函数 /// </summary> /// <param name="pUrl">WebService 地址</param> /// <param name="pClassname">类名,可省略,可空</param> public SoapHelper(string pUrl, string pClassname = null) { if (String.IsNullOrEmpty(pClassname)) WebServiceClassname = GetWsClassName(pUrl); else WebServiceClassname = pClassname; WebServiceNamespace = "LiveAzure.Utility"; try { WebClient wc = new WebClient(); Stream stream = wc.OpenRead(pUrl + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); sdi.ProtocolName = "Soap"; sdi.Style = ServiceDescriptionImportStyle.Client; sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; CodeNamespace cn = new CodeNamespace(this.WebServiceNamespace); SoapCompileUnit = new CodeCompileUnit(); SoapCompileUnit.Namespaces.Add(cn); sdi.Import(cn, SoapCompileUnit); CSharpCodeProvider csc = new CSharpCodeProvider(); SoapCodeProvider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cparam = new CompilerParameters(); cparam.GenerateExecutable = false; cparam.GenerateInMemory = true; cparam.ReferencedAssemblies.Add("System.dll"); cparam.ReferencedAssemblies.Add("System.XML.dll"); cparam.ReferencedAssemblies.Add("System.Web.Services.dll"); cparam.ReferencedAssemblies.Add("System.Data.dll"); SoapCompilerResults = SoapCodeProvider.CompileAssemblyFromDom(cparam, SoapCompileUnit); if (SoapCompilerResults.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in SoapCompilerResults.Errors) { sb.Append(ce.ToString()); sb.Append(Environment.NewLine); } throw new Exception(sb.ToString()); } } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public void Generate() { if (this.AddressType == AddressType.WebService) { string className = MethodHelper.GetClassName(this.Address); //Get wsdl information System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream strm = wc.OpenRead(Address + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(strm); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(this.ComileNamespace); //Generate client proxy class CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //Setting compile parameters CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.XML.dll"); compilerParams.ReferencedAssemblies.Add("System.Web.Services.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.dll"); //compile agentcy class CompilerResults cr = icc.CompileAssemblyFromDom(compilerParams, 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()); } this.ProxyAssemble = cr.CompiledAssembly; Type t = this.ProxyAssemble.GetType(string.Concat(this.ComileNamespace, ".", className), true, true); ServiceObject = Activator.CreateInstance(t); } else { ServiceObject = new NormalRequest(); } SetUrl(this.Address); }
/// <summary> /// 动态调用WebService /// </summary> /// <param name="url">WebService地址</param> /// <param name="classname">类名</param> /// <param name="methodname">方法名(模块名)</param> /// <param name="args">参数列表</param> /// <returns>object</returns> public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "wangsx.test"; if (classname == null || classname == "") { classname = WebServiceHelper.GetClassName(url); } //获取服务描述语言(WSDL) WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL");//【1】 ServiceDescription sd = ServiceDescription.Read(stream);//【2】 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();//【3】 sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace);//【4】 //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit();//【5】 ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider();//【6】 ICodeCompiler icc = csc.CreateCompiler();//【7】 //设定编译器的参数 CompilerParameters cplist = new CompilerParameters();//【8】 cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);//【9】 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new System.Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; System.Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = System.Activator.CreateInstance(t);//【10】 System.Reflection.MethodInfo mi = t.GetMethod(methodname);//【11】 return mi.Invoke(obj, args); }
/// <summary> /// 根据WEBSERVICE地址获取一个 Assembly /// </summary> /// <param name="p_Url">地址</param> /// <param name="p_NameSpace">命名空间</param> /// <returns>返回Assembly</returns> public static Assembly GetWebServiceAssembly(string p_Url, string p_NameSpace) { try { System.Net.WebClient _WebClient = new System.Net.WebClient(); System.IO.Stream _WebStream = _WebClient.OpenRead(p_Url); ServiceDescription _ServiceDescription = ServiceDescription.Read(_WebStream); _WebStream.Close(); _WebClient.Dispose(); ServiceDescriptionImporter _ServiceDescroptImporter = new ServiceDescriptionImporter(); _ServiceDescroptImporter.AddServiceDescription(_ServiceDescription, "", ""); System.CodeDom.CodeNamespace _CodeNameSpace = new System.CodeDom.CodeNamespace(p_NameSpace); System.CodeDom.CodeCompileUnit _CodeCompileUnit = new System.CodeDom.CodeCompileUnit(); _CodeCompileUnit.Namespaces.Add(_CodeNameSpace); _ServiceDescroptImporter.Import(_CodeNameSpace, _CodeCompileUnit); System.CodeDom.Compiler.CodeDomProvider _CodeDom = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters _CodeParameters = new System.CodeDom.Compiler.CompilerParameters(); _CodeParameters.GenerateExecutable = false; _CodeParameters.GenerateInMemory = true; _CodeParameters.ReferencedAssemblies.Add("System.dll"); _CodeParameters.ReferencedAssemblies.Add("System.XML.dll"); _CodeParameters.ReferencedAssemblies.Add("System.Web.Services.dll"); _CodeParameters.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults _CompilerResults = _CodeDom.CompileAssemblyFromDom(_CodeParameters, _CodeCompileUnit); if (_CompilerResults.Errors.HasErrors) { string _ErrorText = ""; foreach (CompilerError _Error in _CompilerResults.Errors) { _ErrorText += _Error.ErrorText + "/r/n"; } throw new Exception(_ErrorText); } return _CompilerResults.CompiledAssembly; } catch (Exception ex) { throw ex; } }
public static object InvokeWebService(string url, string @namespace, string classname, string methodname, object[] args) { try { System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public WebServiceHelper(string Url, string classname) { if ((classname == null) || (classname == string.Empty)) { this.classname = this.GetWsClassName(Url); } else { this.classname = classname; } try { Stream stream = new WebClient().OpenRead(Url + "?WSDL"); ServiceDescription serviceDescription = ServiceDescription.Read(stream); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.AddServiceDescription(serviceDescription, "", ""); CodeNamespace namespace2 = new CodeNamespace(this.@namespace); stream.Close(); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(namespace2); importer.Import(namespace2, codeCompileUnit); ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler(); CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.XML.dll"); options.ReferencedAssemblies.Add("System.Web.Services.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults results = compiler.CompileAssemblyFromDom(options, codeCompileUnit); if (results.Errors.HasErrors) { StringBuilder builder = new StringBuilder(); foreach (CompilerError error in results.Errors) { builder.Append(error.ToString()); builder.Append(Environment.NewLine); } throw new Exception(builder.ToString()); } this.assembly = results.CompiledAssembly; } catch (Exception exception) { throw new Exception(exception.InnerException.Message, new Exception(exception.InnerException.StackTrace)); } }
public static void Test() { try { string _strUrl = uctlBaseConfig.GetConfig("WebServiceUrl"); // 1. 使用 WebClient 下载 WSDL 信息。 WebClient web = new WebClient(); Stream stream = web.OpenRead(_strUrl); // 2. 创建和格式化 WSDL 文档。 ServiceDescription description = ServiceDescription.Read(stream); // 3. 创建客户端代理代理类。 ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap"; // 指定访问协议。 importer.Style = ServiceDescriptionImportStyle.Client; // 生成客户端代理。 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); // 添加 WSDL 文档。 // 4. 使用 CodeDom 编译客户端代理类。 CodeNamespace nmspace = new CodeNamespace(); // 为代理类添加命名空间,缺省为全局空间。 CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; parameter.OutputAssembly = "DynamicWebService.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 result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { // 显示编译错误信息 } //调用程序集文件演示 Assembly asm = Assembly.LoadFrom("DynamicWebService.dll"); Type t = asm.GetType("WebService"); object o = Activator.CreateInstance(t); MethodInfo method = t.GetMethod("HelloWorld"); object oo = method.Invoke(o, null); } catch (Exception ex) { throw; } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // Get the namespace that we will use string ns = Util.GetNamespaceFromVirtualPath(VirtualPathObject); ServiceDescription sd; // Load the wsdl file using (Stream stream = VirtualPathObject.OpenFile()) { try { sd = ServiceDescription.Read(stream); } catch (InvalidOperationException e) { // It can throw an InvalidOperationException, with the relevant // XmlException as the inner exception. If so, throw that instead. XmlException xmlException = e.InnerException as XmlException; if (xmlException != null) throw xmlException; throw; } } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); #if !FEATURE_PAL importer.CodeGenerator = assemblyBuilder.CodeDomProvider; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync; #endif // !FEATURE_PAL importer.ServiceDescriptions.Add(sd); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(ns); codeCompileUnit.Namespaces.Add(codeNamespace); // Create the code compile unit importer.Import(codeNamespace, codeCompileUnit); // Add the CodeCompileUnit to the compilation assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); }
protected override CodeCompileUnit GenerateCode(EndPointSetting wsdl) { if (wsdl == null || string.IsNullOrEmpty(wsdl.Uri)) throw new ApplicationException("WSDL Uri in endpoint section of the configuration is empty."); var wsdlContent = TryGetContent(wsdl.Uri); if(string.IsNullOrEmpty(wsdlContent)) throw new ApplicationException("Could not get content from WSDL at " + wsdl.Uri); var codeCompileUnit = new CodeCompileUnit(); try { var reader = new StringReader(wsdlContent); var serviceDescription = ServiceDescription.Read(reader); var codeNamespace = new CodeNamespace(ProxyGeneratorSettings.Options.Services.Namespace); var importer = new ServiceDescriptionImporter(); RemovePolicyFormat(serviceDescription); importer.ProtocolName = "Soap"; importer.AddServiceDescription(serviceDescription, null, null); AddExternalSchema(serviceDescription, importer); codeCompileUnit.Namespaces.Add(codeNamespace); ServiceDescriptionImportWarnings warning = importer.Import(codeNamespace, codeCompileUnit); if (warning != 0) { Logger.WarnFormat("There was warnings when importing WSDL file at {0}. Warning message is: {1}.", wsdl.Uri, warning); } } catch (Exception ex) { string message = "The wsdl with path:" + wsdl.Uri + " could not be processed.Error during the CodeCompileUnit generation."; throw new ApplicationException(message, ex); } return codeCompileUnit; }
/// <summary> /// ����WebService��URL������һ�����ص�dll,����C�����棬���磺C:|DBMS_WebService.dll /// �����ˣ������� ����ʱ�䣺2010-6-21 /// </summary> /// <param name="url">WebService��UR</param> /// <returns></returns> public static void CreateWebServiceDLL(string url) { string @namespace = "ServiceBase.WebService.DynamicWebLoad"; string classname = WebServiceHelper.GetClassName(url); // 1. ʹ�� WebClient ���� WSDL ��Ϣ�� WebClient web = new WebClient(); Stream stream = web.OpenRead(url + "?WSDL"); // 2. ������ʽ�� WSDL �ĵ��� ServiceDescription description = ServiceDescription.Read(stream); // 3. �����ͻ��˴�������ࡣ ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap"; // ָ������Э�顣 importer.Style = ServiceDescriptionImportStyle.Client; // ���ɿͻ��˴���� importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); // ��� WSDL �ĵ��� // 4. ʹ�� CodeDom ����ͻ��˴����ࡣ CodeNamespace nmspace = new CodeNamespace(@namespace); // Ϊ��������������ռ䣬ȱʡΪȫ�ֿռ䡣 CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; parameter.OutputAssembly = Application.StartupPath + "//DBMS_Service.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 result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { // ��ʾ���������Ϣ System.Text.StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in result.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } }
private static void Init(string Url) { System.Net.WebClient client = new System.Net.WebClient(); string url = Url + "?wsdl";//要訪問的地址 後面要加上:?WSDL System.IO.Stream stream = client.OpenRead(url); System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter importer = new System.Web.Services.Description.ServiceDescriptionImporter();//創建客戶端代理。 importer.ProtocolName = "Soap"; //指定訪問協議。 importer.Style = System.Web.Services.Description.ServiceDescriptionImportStyle.Client; //生成代理。 importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties | System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //添加WSDL文檔 System.CodeDom.CodeNamespace nmspace = new System.CodeDom.CodeNamespace(); //命名空間 nmspace.Name = nameSpace; System.CodeDom.CodeCompileUnit unit = new System.CodeDom.CodeCompileUnit(); unit.Namespaces.Add(nmspace); System.Web.Services.Description.ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); System.CodeDom.Compiler.CodeDomProvider provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); System.CodeDom.Compiler.CompilerParameters parameter = new System.CodeDom.Compiler.CompilerParameters(); parameter.GenerateExecutable = false; parameter.OutputAssembly = "Sms.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"); System.CodeDom.Compiler.CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { //編譯錯誤 } isInited = true; }
private object WebServerAccessMethod(string webserverUrl, string protocolName, string webserverClassName, string webserverMethod, object[] methodParams) { WebClient client = new WebClient(); ServiceDescription serviceDescription = ServiceDescription.Read(client.OpenRead(webserverUrl + "?WSDL")); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); if (protocolName != "") { importer.ProtocolName = protocolName; } else { importer.ProtocolName = "Soap"; } importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties; importer.AddServiceDescription(serviceDescription, null, null); CodeNamespace namespace2 = new CodeNamespace(); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(namespace2); importer.Import(namespace2, codeCompileUnit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters options = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.XML.dll"); options.ReferencedAssemblies.Add("System.Web.Services.dll"); options.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults results = provider.CompileAssemblyFromDom(options, new CodeCompileUnit[] { codeCompileUnit }); if (results.Errors.HasErrors) { return "NO"; } Type type = results.CompiledAssembly.GetType(webserverClassName); object obj2 = Activator.CreateInstance(type); return type.GetMethod(webserverMethod).Invoke(obj2, methodParams); }
private static SoapHttpClientProtocol GenerateService(Stream stream, string serviceName) { var serviceDescription = ServiceDescription.Read(stream); var serviceDescriptionImporter = new ServiceDescriptionImporter { ProtocolName = "Soap12", Style = ServiceDescriptionImportStyle.Client, CodeGenerationOptions = CodeGenerationOptions.GenerateProperties }; serviceDescriptionImporter.AddServiceDescription(serviceDescription, null, null); var codeNamespace = new CodeNamespace(); var codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNamespace); var warnings = serviceDescriptionImporter.Import(codeNamespace, codeCompileUnit); if (warnings > 0) throw new Exception(string.Format("{0}", warnings)); using (var codeDomProvider = CodeDomProvider.CreateProvider("C#")) { var compilerParameters = new CompilerParameters(new[] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" }) { GenerateInMemory = true }; var results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, codeCompileUnit); if (results.Errors.Count > 0) throw new Exception(string.Join(", ", results.Errors.Cast<CompilerError>().Select(e => e.ToString()).ToArray())); var service = results.CompiledAssembly.CreateInstance(serviceName); return service as SoapHttpClientProtocol; } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { ServiceDescription description; string namespaceFromVirtualPath = Util.GetNamespaceFromVirtualPath(base.VirtualPathObject); Stream stream = base.VirtualPathObject.OpenFile(); try { description = ServiceDescription.Read(stream); } catch (InvalidOperationException exception) { XmlException innerException = exception.InnerException as XmlException; if (innerException != null) { throw innerException; } throw; } finally { if (stream != null) { stream.Dispose(); } } ServiceDescriptionImporter importer = new ServiceDescriptionImporter { CodeGenerator = assemblyBuilder.CodeDomProvider, CodeGenerationOptions = CodeGenerationOptions.GenerateOldAsync | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties }; importer.ServiceDescriptions.Add(description); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace namespace2 = new CodeNamespace(namespaceFromVirtualPath); codeCompileUnit.Namespaces.Add(namespace2); importer.Import(namespace2, codeCompileUnit); assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit); }
/// <include file='doc\ServiceDescriptionImporter.uex' path='docs/doc[@for="ServiceDescriptionImporter.GenerateWebReferences1"]/*' /> public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { if (codeCompileUnit != null) { codeCompileUnit.ReferencedAssemblies.Add("System.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll"); } Hashtable namespaces = new Hashtable(); Hashtable exportedMappings = new Hashtable(); foreach (WebReference webReference in webReferences) { ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit); // separate descriptions and schemas XmlSchemas schemas = new XmlSchemas(); ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection(); foreach (DictionaryEntry entry in webReference.Documents) { AddDocument((string)entry.Key, entry.Value, schemas, descriptions, webReference.ValidationWarnings); } importer.Schemas.Add(schemas); foreach (ServiceDescription source in descriptions) { importer.AddServiceDescription(source, webReference.AppSettingUrlKey, webReference.AppSettingBaseUrl); } importer.CodeGenerator = codeProvider; importer.ProtocolName = webReference.ProtocolName; importer.Style = options.Style; importer.CodeGenerationOptions = options.CodeGenerationOptions; foreach (string extensionType in options.SchemaImporterExtensions) { importer.Extensions.Add(Type.GetType(extensionType, true /*throwOnError*/)); } ImportContext context = Context(webReference.ProxyCode, namespaces, options.Verbose); webReference.Warnings = importer.Import(webReference.ProxyCode, context, exportedMappings, webReference.ValidationWarnings); if (webReference.ValidationWarnings.Count != 0) { webReference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation; } } StringCollection shareWarnings = new StringCollection(); if (options.Verbose) { foreach (ImportContext context in namespaces.Values) { foreach (string warning in context.Warnings) { shareWarnings.Add(warning); } } } return(shareWarnings); }
public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, System.CodeDom.CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { if (codeCompileUnit != null) { codeCompileUnit.ReferencedAssemblies.Add("System.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll"); codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll"); } Hashtable namespaces = new Hashtable(); Hashtable exportContext = new Hashtable(); foreach (WebReference reference in webReferences) { ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit); XmlSchemas schemas = new XmlSchemas(); ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection(); foreach (DictionaryEntry entry in reference.Documents) { AddDocument((string) entry.Key, entry.Value, schemas, descriptions, reference.ValidationWarnings); } importer.Schemas.Add(schemas); foreach (ServiceDescription description in descriptions) { importer.AddServiceDescription(description, reference.AppSettingUrlKey, reference.AppSettingBaseUrl); } importer.CodeGenerator = codeProvider; importer.ProtocolName = reference.ProtocolName; importer.Style = options.Style; importer.CodeGenerationOptions = options.CodeGenerationOptions; foreach (string str in options.SchemaImporterExtensions) { importer.Extensions.Add(Type.GetType(str, true)); } System.Xml.Serialization.ImportContext importContext = Context(reference.ProxyCode, namespaces, options.Verbose); reference.Warnings = importer.Import(reference.ProxyCode, importContext, exportContext, reference.ValidationWarnings); if (reference.ValidationWarnings.Count != 0) { reference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation; } } StringCollection strings = new StringCollection(); if (options.Verbose) { foreach (System.Xml.Serialization.ImportContext context2 in namespaces.Values) { foreach (string str2 in context2.Warnings) { strings.Add(str2); } } } return strings; }
[MonoTODO] // where to use Verbose and Extensions in options? public static StringCollection GenerateWebReferences ( WebReferenceCollection webReferences, CodeDomProvider codeGenerator, CodeCompileUnit codeCompileUnit, WebReferenceOptions options) { StringCollection allWarnings = new StringCollection (); ImportContext context = new ImportContext (new CodeIdentifiers(), true); foreach (WebReference reference in webReferences) { ServiceDescriptionImporter importer = new ServiceDescriptionImporter (); if (codeGenerator != null) importer.CodeGenerator = codeGenerator; importer.CodeGenerationOptions = options.CodeGenerationOptions; importer.Context = context; importer.Style = options.Style; importer.ProtocolName = reference.ProtocolName; importer.AddReference (reference); reference.Warnings = importer.Import (reference.ProxyCode, codeCompileUnit); reference.SetValidationWarnings (context.Warnings); foreach (string s in context.Warnings) allWarnings.Add (s); context.Warnings.Clear (); } return allWarnings; }
/// <summary> /// 使用指定的参数调用所指定 WebService 类的指定方法。 /// </summary> /// <param name="url">地址</param> /// <param name="className">类名</param> /// <param name="methodName">方法名</param> /// <param name="args">参数</param> /// <returns></returns> public static object InvokeWebService(string url, string className, string methodName, object[] args) { var dynamicWebCallingNamespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if (!url.EndsWith("?WSDL", StringComparison.OrdinalIgnoreCase)) { url += "?WSDL"; } if (string.IsNullOrEmpty(className)) { className = GetWebCallingClassName(url); } var webClient = new WebClient(); var stream = webClient.OpenRead(url); var svcDesc = ServiceDescription.Read(stream); var svcDescIpt = new ServiceDescriptionImporter(); svcDescIpt.AddServiceDescription(svcDesc, string.Empty, string.Empty); var codeCompileUnit = new CodeCompileUnit(); var codeNamespace = new CodeNamespace(dynamicWebCallingNamespace); codeCompileUnit.Namespaces.Add(codeNamespace); svcDescIpt.Import(codeNamespace, codeCompileUnit); var cSharpCodeProvider = new CSharpCodeProvider(); var compilerParams = new CompilerParameters(); compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.XML.dll"); compilerParams.ReferencedAssemblies.Add("System.Web.Services.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.dll"); var codeDomProvider = CodeDomProvider.CreateProvider("CSharp"); var compilerResults = codeDomProvider.CompileAssemblyFromDom(compilerParams, codeCompileUnit); if (compilerResults.Errors.HasErrors) { var msg = new StringBuilder(); foreach (CompilerError error in compilerResults.Errors) { msg.AppendLine(error.ToString()); } throw new Exception(msg.ToString()); } var assembly = compilerResults.CompiledAssembly; var type = assembly.GetType(dynamicWebCallingNamespace + "." + className, true, true); var obj = Activator.CreateInstance(type); var methodInfo = type.GetMethod(methodName); return methodInfo.Invoke(obj, args); }
static Type GetTypeFromWebService(string url, string className) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((className == null) || (className == "")) { className = GetWsClassName(url); } //http://blog.csdn.net/lzy_1515 //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + className, true, true); return t; }
//DONE //This method generates proxy code from a webservice's WSDL file, compiles and assembles it. It returns the compiled on success, //null on failure. private CompilerResults GenerateProxyWebService(string webServiceURL) { string[] assemblyReferences = {"System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll"}; CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeNamespace webNameSpace = new CodeNamespace(); CodeCompileUnit compileUnit = new CodeCompileUnit(); ServiceDescriptionImporter webServiceImporter = new ServiceDescriptionImporter(); WebClient webServiceClient = new WebClient(); try { //Connect to new web service through the passed URL... Stream serviceStream = webServiceClient.OpenRead(webServiceURL + "?wsdl"); //This gets the WSDL file... ServiceDescription webServiceDescription = ServiceDescription.Read(serviceStream); //Initalize the importer... webServiceImporter.ProtocolName = "Soap"; webServiceImporter.AddServiceDescription(webServiceDescription, null, null); //Generate the proxy code webServiceImporter.Style = ServiceDescriptionImportStyle.Client; webServiceImporter.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; //Initialize the Code-DOM tree compileUnit.Namespaces.Add(webNameSpace); //Import the service ServiceDescriptionImportWarnings importWarning = webServiceImporter.Import(webNameSpace, compileUnit); //If no warnings... if (importWarning == 0) { //Generate code... CompilerParameters compilerParameters = new CompilerParameters(assemblyReferences); compilerParameters.GenerateInMemory = true; CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, compileUnit); if (compilerResults.Errors.Count > 0) { throw new System.Exception("Compiler error occured when calling webservice..."); } return compilerResults; } return null; } catch (Exception ex) { throw ex; } }