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; } } }
public static Object InvokeWebService(String url, String classname, String methodname, Object[] args) { String @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if (String.IsNullOrEmpty(classname)) { classname = WebServiceHelper.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 import = new CompilerParameters(); import.GenerateExecutable = false; import.GenerateInMemory = true; import.ReferencedAssemblies.Add("System.dll"); import.ReferencedAssemblies.Add("System.XML.dll"); import.ReferencedAssemblies.Add("System.Web.Services.dll"); import.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(import, 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()); } //生成代理实例,并调用方法 Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); Object obj = Activator.CreateInstance(t); MethodInfo mi = t.GetMethod(methodname); return(mi.Invoke(obj, args)); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
private void GenerateCode(ServiceDescriptionCollection sources, XmlSchemas schemas, string uriToWSDL, CodeDomProvider codeGen, string fileExtension) { this.proxyCode = " <ERROR> "; StringWriter w = null; this.compileUnit = new CodeCompileUnit(); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.Schemas.Add(schemas); foreach (ServiceDescription description in sources) { importer.AddServiceDescription(description, "", ""); } importer.Style = ServiceDescriptionImportStyle.Client; Protocol protocol = this.WsdlProperties.Protocol; importer.ProtocolName = this.WsdlProperties.Protocol.ToString(); CodeNamespace namespace2 = new CodeNamespace(this.proxyNamespace); this.compileUnit.Namespaces.Add(namespace2); ServiceDescriptionImportWarnings warnings = importer.Import(namespace2, this.compileUnit); try { try { w = new StringWriter(); } catch { throw; } MemoryStream stream = null; if (schemas.Count > 0) { this.compileUnit.ReferencedAssemblies.Add("System.Data.dll"); foreach (XmlSchema schema in schemas) { string targetNamespace = null; try { targetNamespace = schema.TargetNamespace; if (XmlSchemas.IsDataSet(schema)) { if (stream == null) { stream = new MemoryStream(); } stream.Position = 0L; stream.SetLength(0L); schema.Write(stream); stream.Position = 0L; DataSet dataSet = new DataSet(); dataSet.ReadXmlSchema(stream); System.Data.Design.TypedDataSetGenerator.Generate(dataSet, namespace2, codeGen); } continue; } catch { throw; } } } try { GenerateVersionComment(this.compileUnit.Namespaces[0]); this.ChangeBaseType(this.compileUnit); codeGen.GenerateCodeFromCompileUnit(this.compileUnit, w, null); } catch (Exception exception) { if (w != null) { w.Write("Exception in generating code"); w.Write(exception.Message); } throw new InvalidOperationException("Error generating ", exception); } } finally { this.proxyCode = w.ToString(); if (w != null) { w.Close(); } } }
private string InvokeMethod(string wsdl_text,string MethodName,Object[] param1) { try { Uri uri = new Uri(wsdl_text); 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()); // 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); MethodInfo[] methodinfo = service.GetMethods(); string result = null; foreach (MethodInfo t in methodinfo) if (t.Name == MethodName) { //Invoke Method Object obj = Activator.CreateInstance(service); Object response = t.Invoke(obj, param1); Array myArrayList = response as Array; if (myArrayList != null) { List<Object> result_obj = new List<Object>(); foreach (var item in myArrayList) { foreach (var currentPropertyInformation in item.GetType().GetProperties()) { //currentPropertyInformation.GetValue(item, null); //Result.Text = Result.Text + currentPropertyInformation.Name + ":" + currentPropertyInformation.GetValue(item, null); result = currentPropertyInformation.GetValue(item, null).ToString(); } } } else if(response.GetType().ToString() != "System.String") { foreach (var currentPropertyInformation in response.GetType().GetProperties()) { //currentPropertyInformation.GetValue(item, null); //Result.Text = Result.Text + currentPropertyInformation.Name + ":" + currentPropertyInformation.GetValue(item, null); if (currentPropertyInformation.GetValue(response, null) != null) { result = result + currentPropertyInformation.Name + ":" + currentPropertyInformation.GetValue(response, null) + "|"; } else { result = result + currentPropertyInformation.Name + ":NULL,"; } } } if(response!=null && result==null) { result = response.ToString(); } break; } return result; } else { return null; } } catch (Exception ex) { return null; } }
/// <summary> /// 得到WSDL信息,生成本地代理类并编译为DLL /// </summary> private void CreateServiceAssembly() { if (this.checkCache()) { this.initTypeName(); return; } if (string.IsNullOrEmpty(this._wsdlUrl)) { return; } try { //使用WebClient下载WSDL信息 WebClient web = new WebClient(); Stream stream = web.OpenRead(this._wsdlUrl); ServiceDescription description = ServiceDescription.Read(stream); //创建和格式化WSDL文档 ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //创建客户端代理代理类 importer.ProtocolName = "Soap"; importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //使用CodeDom编译客户端代理类 CodeNamespace nmspace = new CodeNamespace(_assName); //为代理类添加命名空间 CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); this.checkForImports(this._wsdlUrl, importer); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); parameter.GenerateExecutable = false; parameter.GenerateInMemory = false; parameter.IncludeDebugInformation = false; //1.生成cs TextWriter writer = File.CreateText(this._assCsTmp); provider.GenerateCodeFromCompileUnit(unit, writer, null); writer.Flush(); writer.Close(); //2.修改cs中连接的端口 RefreshPort(); CompilerResults result = provider.CompileAssemblyFromFile(parameter, this._assCs); //如果存在端口隐射的问题,先生成CS,修改cs中的端口 在根据cs生成dll provider.Dispose(); if (result.Errors.HasErrors) { string errors = string.Format(@"编译错误:{0}错误!", result.Errors.Count); foreach (CompilerError error in result.Errors) { errors += error.ErrorText; } throw new Exception(errors); } this.copyTempAssembly(result.PathToAssembly); this.initTypeName(); //删除cs临时文件 File.Delete(_assCs); File.Delete(_assCsTmp); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public static object InvokeWebService(string string_0, string string_1, params object[] args) { object obj4; string name = "Aisino.WebService.DynamicWebCalling"; Stream stream = null; WebClient client = null; CSharpCodeProvider provider = null; try { if (!dictionary_0.ContainsKey(string_0)) { client = new WebClient(); stream = client.OpenRead(string_0 + "?WSDL"); ServiceDescription serviceDescription = ServiceDescription.Read(stream); string key = serviceDescription.Services[0].Name; ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.AddServiceDescription(serviceDescription, "", ""); CodeNamespace namespace2 = new CodeNamespace(name); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(namespace2); importer.Import(namespace2, codeCompileUnit); 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"); provider = new CSharpCodeProvider(); CompilerResults results = provider.CompileAssemblyFromDom(options, new CodeCompileUnit[] { 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; Dictionary <string, Assembly> dictionary = new Dictionary <string, Assembly>(); dictionary.Add(key, compiledAssembly); dictionary_0.Add(string_0, dictionary); } Dictionary <string, Assembly> dictionary2 = dictionary_0[string_0]; Assembly assembly2 = null; string str3 = null; foreach (KeyValuePair <string, Assembly> pair in dictionary2) { str3 = pair.Key; assembly2 = pair.Value; } Type type = assembly2.GetType(name + "." + str3, true, true); object obj2 = Activator.CreateInstance(type); obj4 = type.GetMethod(string_1).Invoke(obj2, args); } catch (Exception exception) { throw new Exception(exception.InnerException.Message, new Exception(exception.InnerException.StackTrace)); } finally { if (stream != null) { stream.Close(); stream.Dispose(); } if (client != null) { client.Dispose(); } if (provider != null) { provider.Dispose(); } } return(obj4); }
public WebServiceClientHelper(string url, string spacename, string classname) { try { _serviceURL = url; _serviceClassName = classname; _serviceNameSpace = spacename; if (Utility.IsAnyNullOrEmpty(spacename, classname)) { Common.LogHelper.Instance.WriteError("调用目标地址或命名空间为空."); _webServiceConnectedFlag = false; return; } string _namespace = _serviceNameSpace; if (string.IsNullOrEmpty(classname)) { classname = GetClassName(_serviceURL); } //获取服务描述语言(WSDL) WebClient wc = new WebClient(); Stream stream = wc.OpenRead(_serviceURL + "?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); CodeDomProvider csc = CodeDomProvider.CreateProvider("CSharp"); //设定编译器的参数 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 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; _webServiceType = assembly.GetType(_namespace + "." + classname, true, true); _webServiceObject = Activator.CreateInstance(_webServiceType); _webServiceConnectedFlag = true; } catch (Exception) { _webServiceConnectedFlag = false; throw; } }
/// <summary> /// Uses codedom to create the webservice test DLL and execute a method provided /// against the web service. /// </summary> /// <param name="webServiceAsmxUrl">Web Service URL</param> /// <param name="serviceName">Web Service Name</param> /// <param name="methodName">Method Name</param> /// <param name="args">Method Arguments</param> /// <returns>Web Service Response Object</returns> public object Testwsurl(string webServiceAsmxUrl, string serviceName, string methodName, object[] args) { args = new object[] { "Success" }; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(webServiceAsmxUrl); webRequest.Timeout = 10000; webRequest.UserAgent = "TerraScan Treasurer"; HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); Encoding enc = System.Text.Encoding.GetEncoding(1252); StreamReader responseStreamlo = new StreamReader(webResponse.GetResponseStream(), enc); string response = responseStreamlo.ReadToEnd(); responseStreamlo.Close(); webResponse.Close(); // MessageBox.Show(Response); // return webResponse; System.Net.WebClient client = new System.Net.WebClient(); // -Connect To the web service System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl"); // --Now read the WSDL file describing a // service. System.Web.Services.Description.ServiceDescription description = ServiceDescription.Read(stream); ///// LOAD THE DOM ///////// // --Initialize a service description importer. ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap12"; // Use SOAP 1.2. importer.AddServiceDescription(description, null, null); // --Generate a proxy client. importer.Style = ServiceDescriptionImportStyle.Client; // --Generate properties to represent pri // mitive values. importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; // --Initialize a Code-DOM tree into which we will import the service. CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit unit1 = new CodeCompileUnit(); unit1.Namespaces.Add(nmspace); // --Import the service into the Code-DOM tree. // --This creates proxy code that uses the service. ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1); if (warning == 0) // --If zero then we are good to go { // --Generate the proxy code CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp"); // --Compile the assembly proxy with the appropriate references string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" }; CompilerParameters parms = new CompilerParameters(assemblyReferences); CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1); // -Check For Errors if (results.Errors.Count > 0) { foreach (CompilerError oops in results.Errors) { System.Diagnostics.Debug.WriteLine("========Compiler error============"); System.Diagnostics.Debug.WriteLine(oops.ErrorText); } throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window."); } // --Finally, Invoke the web service method object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName); MethodInfo mi = wsvcClass.GetType().GetMethod(methodName); return(mi.Invoke(wsvcClass, args)); } else { return(null); } }
/// <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); } } }
public byte[] CreateRefDll(string Ipadd) { WebClient web = new WebClient(); web.Proxy = null; Dictionary <string, ServiceDescription> dicdescription = new Dictionary <string, ServiceDescription>(); XmlDocument doc = new XmlDocument(); string XmlName = "DllConfig.xml"; string dllname = "getWebServices.dll"; doc.Load(Server.MapPath("") + "\\" + XmlName); if (File.Exists(Server.MapPath("") + "\\" + dllname)) { File.Delete(Server.MapPath("") + "\\" + dllname); } string ServerURL = string.Format("http://{0}/{1}/", Ipadd, ((XmlElement)doc.SelectSingleNode("AutoCreate").SelectSingleNode("ServerPath")).GetAttribute("PATH")); CodeCompileUnit unit = new CodeCompileUnit(); foreach (XmlNode xn in doc.SelectSingleNode("AutoCreate").SelectSingleNode("FileList").ChildNodes) { string _temp = ((XmlElement)xn).GetAttribute("Name"); if (!string.IsNullOrEmpty(_temp)) { dicdescription.Add(string.Format("WebServices.{0}", _temp.Split('.')[0]), ServiceDescription.Read(web.OpenRead(string.Format("{0}{1}?WSDL", ServerURL, _temp)))); } } foreach (string str in dicdescription.Keys) { CodeNamespace nmspace = new CodeNamespace(); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap"; importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; nmspace.Name = str; unit.Namespaces.Add(nmspace); importer.AddServiceDescription(dicdescription[str], null, null); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); } CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; parameter.OutputAssembly = Server.MapPath("") + "\\" + dllname; 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); StringBuilder err = new StringBuilder(50000); if (result.Errors.HasErrors) { for (int i = 0; i < result.Errors.Count; i++) { err.AppendLine(result.Errors[i].ErrorText); } } if (string.IsNullOrEmpty(err.ToString())) { return(File.ReadAllBytes(Server.MapPath("") + "\\" + dllname)); } else { return(null); } }
public static object InvokeWebService(string url, string classname, string methodname, object[] args, string import) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceTool.GetWsClassName(url); } //try //{ //获取WSDL WebClient wc = new WebClient(); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); if (!url.ToLower().Contains("?wsdl")) { url = url + "?wsdl"; } Stream stream = wc.OpenRead(url); ServiceDescription sd = ServiceDescription.Read(stream); sdi.AddServiceDescription(sd, "", ""); if (import != "") { string[] urls = import.Split(','); foreach (string addr in urls) { string u = addr; if (!addr.ToLower().Contains("?wsdl")) { u = addr + "?wsdl"; } stream = wc.OpenRead(u); sd = ServiceDescription.Read(stream); sdi.AddServiceDescription(sd, "", ""); } } CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider icc = 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; string sb1 = ""; foreach (var t1 in assembly.GetTypes()) { sb1 += t1.Name + " || "; } //throw new Exception(sb1); //return null; 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> /// 动态调用web服务 /// </summary> /// <param name="url">WSDL服务地址</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, Dictionary <string, object> args) { string @namespace = ""; if ((classname == null) || (classname == "")) { classname = GetWsClassName(url); } try { //获取WSDL var wc = new WebClient(); var stream = wc.OpenRead(url + "?WSDL"); var sd = ServiceDescription.Read(stream); var sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); var cn = new CodeNamespace(@namespace); //生成客户端代理类代码 var ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); var icc = new CSharpCodeProvider(); //设定编译参数 var 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"); //编译代理类 var cr = icc.CompileAssemblyFromDom(cplist, ccu); if (cr.Errors.HasErrors) { var sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce); sb.Append(Environment.NewLine); } throw new System.Exception(sb.ToString()); } //生成代理实例,并调用方法 var assembly = cr.CompiledAssembly; var t = assembly.GetType(@namespace + "." + classname, true, true); var service = Activator.CreateInstance(t); var methodInfo = t.GetMethod(methodname); var paramsInfo = methodInfo.GetParameters(); if (paramsInfo.Length != args.Count) { throw new System.Exception("参数个数不匹配!"); } var obj = new List <object>(); for (int i = 0; i < paramsInfo.Length; i++) { obj.Add(CoralConvert.Convert(args[paramsInfo[i].Name], paramsInfo[i].ParameterType)); } return(methodInfo.Invoke(service, obj.ToArray())); } catch (System.Exception ex) { throw new System.Exception(ex.Message, new System.Exception(ex.StackTrace)); } }
/// <summary> /// 获取实例对象 /// </summary> /// <param name="url">服务地址</param> /// <param name="classname">类名</param> /// <returns>返回结果</returns> public static object GetClassInstance(string url, string classname) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceHelper.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential("guest", "123"); 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 = 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); return(obj); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
/// <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 InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceHelper.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); //注意classname一定要赋值获取 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 icc = new CSharpCodeProvider(); //设定编译参数 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; string newpath = System.Environment.CurrentDirectory + "\\" + getMd5Sum(url) + ".dll"; //if (!File.Exists(newpath)) //{ // File.Copy(cr.PathToAssembly, System.Environment.CurrentDirectory + "\\" + getMd5Sum(url) + ".dll"); //} 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)); // return "Error:WebService调用错误!" + ex.Message; } }
private static Assembly CreateProxyAssembly(string wsdlUrl, string serviceName, string className) { try { //使用WebClient下载WSDL信息 var web = new WebClient(); var stream = web.OpenRead(wsdlUrl); var description = ServiceDescription.Read(stream); //创建和格式化WSDL文档 //创建客户端代理代理类 var importer = new ServiceDescriptionImporter { ProtocolName = "Soap", Style = ServiceDescriptionImportStyle.Client, CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync }; importer.AddServiceDescription(description, null, null); //添加WSDL文档 //使用CodeDom编译客户端代理类 var nmspace = new CodeNamespace(serviceName); //为代理类添加命名空间 var unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); CheckForImports(wsdlUrl, importer); var warning = importer.Import(nmspace, unit); if (warning != 0) { throw new Exception(warning.ToString()); } var provider = CodeDomProvider.CreateProvider("CSharp"); var parameter = new CompilerParameters(); parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); parameter.GenerateExecutable = false; parameter.GenerateInMemory = false; parameter.IncludeDebugInformation = false; var result = provider.CompileAssemblyFromDom(parameter, unit); provider.Dispose(); if (result.Errors.HasErrors) { var errors = string.Format(@"编译错误:{0}错误!", result.Errors.Count); errors = result.Errors.Cast <CompilerError>().Aggregate(errors, (current, error) => current + error.ErrorText); throw new Exception(errors); } return(result.CompiledAssembly); } catch (Exception ex) { throw ex; } }
private void Webservicecall(string contryname) { WebRequest webRequest = WebRequest.Create("http://www.webservicex.net/country.asmx?WSDL"); WebResponse webResponse = webRequest.GetResponse(); // Stream stream = webResponse.GetResponseStream(); ServiceDescription description = new ServiceDescription(); using (Stream stream = webResponse.GetResponseStream()) { description = ServiceDescription.Read(stream); } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap12";//' Use SOAP 1.2. importer.AddServiceDescription(description, null, null); importer.Style = ServiceDescriptionImportStyle.Client; //'--Generate properties to represent primitive values. importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; //'Initialize a Code-DOM tree into which we will import the service. CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit unit1 = new CodeCompileUnit(); unit1.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1); CodeDomProvider provider1 = CodeDomProvider.CreateProvider("C#"); //'--Compile the assembly proxy with the // appropriate references String[] assemblyReferences; assemblyReferences = new String[] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" }; CompilerParameters parms = new CompilerParameters(assemblyReferences); parms.GenerateInMemory = true; CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1); if (results.Errors.Count > 0) { } Type foundType = null; Type[] types = results.CompiledAssembly.GetTypes(); foreach (Type type1 in types) { if (type1.BaseType == typeof(SoapHttpClientProtocol)) { foundType = type1; } } if (!String.IsNullOrEmpty(contryname)) { Object[] args = new Object[1]; args[0] = contryname; Object wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString()); MethodInfo mi = wsvcClass.GetType().GetMethod("GetCurrencyByCountry"); var returnValue = mi.Invoke(wsvcClass, args); DataSet ds = new DataSet(); grdcountrydata.DataSource = ConvertXMLToDataSet(returnValue.ToString()); grdcountrydata.DataBind(); } else { Object wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString()); MethodInfo mi = wsvcClass.GetType().GetMethod("GetCountries"); var returnValue = mi.Invoke(wsvcClass, null); DataSet ds = new DataSet(); grdcountry.DataSource = ConvertXMLToDataSet(returnValue.ToString()); grdcountry.DataBind(); } }
/// <summary> /// 得到WSDL信息,生成本地代理类并编译为DLL /// </summary> private void CreateServiceAssembly() { if (this.checkCache()) { this.initTypeName(); return; } if (string.IsNullOrEmpty(this._wsdlUrl)) { return; } try { //使用WebClient下载WSDL信息 WebClient web = new WebClient(); Stream stream = web.OpenRead(this._wsdlUrl); ServiceDescription description = ServiceDescription.Read(stream); //创建和格式化WSDL文档 ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //创建客户端代理代理类 importer.ProtocolName = "Soap"; importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //添加WSDL文档 //使用CodeDom编译客户端代理类 // MISLog.GetInstance().Write(MISLog.MSG_LEVEL.FLUSH, "CodeNamespace"); CodeNamespace nmspace = new CodeNamespace(_assName); //为代理类添加命名空间 CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); this.checkForImports(this._wsdlUrl, importer); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); parameter.GenerateExecutable = false; parameter.GenerateInMemory = false; parameter.IncludeDebugInformation = false; CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); provider.Dispose(); if (result.Errors.HasErrors) { string errors = string.Format(@"编译错误:{0}错误!", result.Errors.Count); foreach (CompilerError error in result.Errors) { errors += error.ErrorText; } // MISLog.GetInstance().Write(MISLog.MSG_LEVEL.FLUSH, errors); } this.copyTempAssembly(result.PathToAssembly); this.initTypeName(); } catch (Exception e) { // MISLog.GetInstance().Write(MISLog.MSG_LEVEL.FLUSH, e.ToString()); } }
/// <summary> /// 带服务地址构造函数 /// </summary> /// <param name="serviceUrl">服务地址</param> public CoreWebService(string serviceUrl) { try { var service = new Uri(serviceUrl); var fileName = $"{service.Host}_{service.Port}"; // ReSharper disable once StringLiteralTypo fileName = service.Segments.Select(s => s.Trim('/')).Where(name => !string.IsNullOrEmpty(name)).Aggregate(fileName, (current, name) => current + $"_{name}").Replace(".asmx", string.Empty); var wsdlFile = Path.Combine(_webServiceWsdl, fileName); if (!File.Exists(wsdlFile)) { var file = GetWsdl(serviceUrl); if (!Directory.Exists(_webServiceWsdl)) { Directory.CreateDirectory(_webServiceWsdl); } File.WriteAllText(wsdlFile, file); } var wc = new WebClient(); var stream = wc.OpenRead(wsdlFile); wc.Dispose(); var sd = ServiceDescription.Read(stream ?? throw new InvalidOperationException()); var classname = sd.Services[0].Name; var sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, string.Empty, string.Empty); var cn = new CodeNamespace(); //生成客户端代理类代码 var ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); var csc = new CSharpCodeProvider(); //设定编译参数 var plist = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; //动态编译后的程序集不生成可执行文件 //动态编译后的程序集只存在于内存中,不在硬盘的文件上 plist.ReferencedAssemblies.Add("System.dll"); plist.ReferencedAssemblies.Add("System.XML.dll"); plist.ReferencedAssemblies.Add("System.Web.Services.dll"); plist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 var cr = csc.CompileAssemblyFromDom(plist, ccu); if (cr.Errors.HasErrors) { var sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce); sb.Append(Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 var assembly = cr.CompiledAssembly; _type = assembly.GetType(classname, true, true); } catch (Exception e) { throw new Exception("CoreWebService Err", e); } }
void GetServiceDetails() { var url = Request["service"]; if (string.IsNullOrEmpty(url)) { return; } if (!url.ToLowerInvariant().EndsWith("?wsdl")) url += "?wsdl"; try { using (WebClient wc = new WebClient()) { string content = wc.DownloadString(url); var des = wc.DownloadString(url); var sd = ServiceDescription.Read(new StringReader(des)); ServiceDescriptionImporter im = new ServiceDescriptionImporter(); im.AddServiceDescription(sd, null, null); im.Style = ServiceDescriptionImportStyle.Client; im.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; CodeNamespace ns = new CodeNamespace(); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); ServiceDescriptionImportWarnings warning = im.Import(ns, unit); if (warning == 0) { var domProvider = CodeDomProvider.CreateProvider("CSharp"); var assemblyReferences = new string[] { "System.Web.Services.dll", "System.Xml.dll" }; var parms = new CompilerParameters(assemblyReferences); var results = domProvider.CompileAssemblyFromDom(parms, unit); if (results.Errors.Count > 0) { Response.Output.WriteLine("{ 'error' : ["); foreach (CompilerError ce in results.Errors) { Response.Output.WriteLine("'{0}',", Utils.EscapeString(ce.ErrorText)); } Response.Output.WriteLine("]}"); } object o = results.CompiledAssembly.CreateInstance("WebService"); Type t = o.GetType(); } else { Console.WriteLine("Warning: " + warning); } } } catch (Exception e) { Response.Output.WriteLine("{{ 'error' : '{0}' }}", Utils.EscapeString(e.Message)); } }
/// <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(); }
/// <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); }
private static void GenerateProxy(Action <object, Type> del) { if (null == del) { throw new ArgumentNullException("del"); } try { if (null == HttpContext.Current) { return; } var proxy = HttpContext.Current.Cache[CACHE_KEY]; if (null == proxy) { var spUrl = HttpContext.Current.Request.QueryString["SPHostUrl"]; if (string.IsNullOrEmpty(spUrl)) { spUrl = HttpContext.Current.Request.Form["SPHostUrl"]; } if (string.IsNullOrEmpty(spUrl)) { return; } var wsUrl = string.Format("{0}/_vti_bin/Diagnostics.asmx?wsdl", spUrl); var request = (HttpWebRequest)WebRequest.Create(wsUrl); request.Credentials = CredentialCache.DefaultCredentials; var response = (HttpWebResponse)request.GetResponse(); using (var stream = response.GetResponseStream()) { // Get a WSDL file describing a service. var serviceDescription = ServiceDescription.Read(stream); // Initialize a service description importer. var importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap12"; // Use SOAP 1.2. importer.AddServiceDescription(serviceDescription, null, null); // Report on the service descriptions. Debug.WriteLine("Importing {0} service descriptions with {1} associated schemas.", importer.ServiceDescriptions.Count, importer.Schemas.Count); // Generate a proxy client. importer.Style = ServiceDescriptionImportStyle.Client; // Generate properties to represent primitive values. importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; // Initialize a Code-DOM tree into which we will import the service. var nmspace = new CodeNamespace(); var unit1 = new CodeCompileUnit(); unit1.Namespaces.Add(nmspace); // Import the service into the Code-DOM tree. This creates proxy code // that uses the service. var warning = importer.Import(nmspace, unit1); if (0 == warning) { // Generate and print the proxy code in C#. var provider1 = CodeDomProvider.CreateProvider("CSharp"); // Compile the assembly with the appropriate references string[] assemblyReferences = new string[] { "System.Web.Services.dll", "System.Xml.dll", "System.dll" }; var parms = new CompilerParameters(assemblyReferences); var results = provider1.CompileAssemblyFromDom(parms, unit1); foreach (CompilerError oops in results.Errors) { Debug.WriteLine("======== Compiler error ============"); Debug.WriteLine(oops.ErrorText); } //Invoke the web service method proxy = results.CompiledAssembly.CreateInstance("SharePointDiagnostics"); if (null == proxy) { throw new Exception("Failed to instantiate web service proxy"); } // Add proxy to cache. HttpContext.Current.Cache.Insert(CACHE_KEY, proxy, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration); } else { Debug.WriteLine("Warning: " + warning); } } } del(proxy, proxy.GetType()); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
/// <summary> /// 获取服务端返回的wsdl源代码 /// </summary> /// <param name="swdlAdress"></param> /// <param name="?"></param> /// <returns></returns> public string GetOriginTypeCode(string swdlAdress, out string originTypeName) { try { WebClient client = new WebClient(); string url = swdlAdress; //读取服务端地址的代码内容 Stream stream = client.OpenRead(url); ServiceDescription description = ServiceDescription.Read(stream); stream.Close(); string svcName = description.Services[0].Name; string svcNameSpace = "ChaYeFeng"; if (description.Services.Count == 0) { throw new Exception(string.Format("\"{0}\"没有定义服务", swdlAdress)); } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //指定访问协议 importer.ProtocolName = "Soap"; //指定生成代码的样式(客户端/服务器) importer.Style = ServiceDescriptionImportStyle.Client; //设置代码生成的各种选项 importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.None; //添加要导入的wsdl文档 importer.AddServiceDescription(description, null, null); //命名空间 CodeNamespace nameSpace = new CodeNamespace(); nameSpace.Name = svcNameSpace; //代码的容器 CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nameSpace); //以编程的方式调用xml web services提供支持的类 DiscoveryClientProtocol dcp = new DiscoveryClientProtocol(); //确定url是否为包含有服务说明文档 dcp.DiscoverAny(url); //解析所有发现的文档,xml架构定义和服务说明 dcp.ResolveAll(); foreach (object value in dcp.Documents.Values) { if (value is ServiceDescription) { importer.AddServiceDescription(value as ServiceDescription, null, null); } if (value is XmlSchema) { importer.Schemas.Add(value as XmlSchema); } } //导入相应的参数来生成代码 ServiceDescriptionImportWarnings warning = importer.Import(nameSpace, unit); //代码生成器 CSharpCodeProvider provider = new CSharpCodeProvider(); //调用编译器的参数 CompilerParameters parameter = new CompilerParameters { //是否生成可执行文件 GenerateExecutable = false, //是否在内存中生成输出 GenerateInMemory = true }; //添加当前项目引用的程序集 parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); TextWriter stringWriter = new StringWriter(); //未指定的代码文档对象编译单元生成代码,并使用指定的选项将代码发送到文本编写器 provider.GenerateCodeFromCompileUnit(unit, stringWriter, null); originTypeName = svcName; return(stringWriter.ToString()); } catch (Exception ex) { throw; } }
/// <summary> /// 生成WebService的代理类 /// </summary> /// <param name="url">服务地址</param> /// <param name="namespace">命名空间</param> /// <param name="classname">类名</param> /// <param name="methodname">方法名</param> private void CreateWebservice(string url, string @namespace, string classname, string methodname) { //创建 string URL = string.Empty; if ((url.Substring(url.Length - 4, 4) != null) && ((url.Substring(url.Length - 4, 4).ToLower() != "wsdl"))) { if (url.IndexOf(".asmx") > -1) { m_url = url + "?WSDL"; } else { m_url = url + "WSDL"; } } else { m_url = url; } stream = wc.OpenRead(m_url); sd = ServiceDescription.Read(stream); sdi.AddServiceDescription(sd, "", ""); cn = new CodeNamespace(@m_namespace); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //icc = CodeDomProvider.CreateProvider("CSharp").CreateCompiler();// CSharpCodeProvider.CreateProvider("CSharp").CreateCompiler(); //csc.CreateCompiler(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; if (cplist.ReferencedAssemblies.IndexOf("System.dll") < 0) { cplist.ReferencedAssemblies.Add("System.dll"); } if (cplist.ReferencedAssemblies.IndexOf("System.XML.dll") < 0) { cplist.ReferencedAssemblies.Add("System.XML.dll"); } if (cplist.ReferencedAssemblies.IndexOf("System.Web.Services.dll") < 0) { cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); } if (cplist.ReferencedAssemblies.IndexOf("System.Data.dll") < 0) { cplist.ReferencedAssemblies.Add("System.Data.dll"); } //cr=icc.CompileAssemblyFromDom(cplist, ccu); cr = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } assembly = cr.CompiledAssembly; t = assembly.GetType(@m_namespace + "." + m_classname, true, true); obj = Activator.CreateInstance(t); if (m_methodname.Length > 0) { mi = t.GetMethod(m_methodname); } }
/// <summary> /// InvokeWebService /// </summary> /// <returns></returns> public object InvokeWebService() { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; string classname = this.GetWsClassName(this.url); try { NetworkCredential myCredential = new NetworkCredential(this.username, this.password, this.domain); //获取WSDL WebClient wc = new WebClient(); if (this.needCredential) { wc.Credentials = myCredential; } System.IO.Stream stream = wc.OpenRead(this.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); CodeDomProvider csc = CodeDomProvider.CreateProvider("C#"); //设定编译参数 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 (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); if (this.needCredential) { System.Reflection.PropertyInfo pi = t.GetProperty("Credentials"); pi.SetValue(obj, myCredential, null); } System.Reflection.MethodInfo mi = t.GetMethod(this.methodName); return(mi.Invoke(obj, args)); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public object Invoke(string action, object[] args) { WebClient wc = new WebClient(); using (Stream stream = wc.OpenRead(url + "?WSDL")) { ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(nameSpace); string typeName = ""; string[] parts = url.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); typeName = pps[0]; //生成客户端代理类代码 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 + "." + typeName, true, true); object obj = Activator.CreateInstance(t); #region soapheader信息 FieldInfo[] arry = t.GetFields(); FieldInfo fieldHeader = null; //soapheader 对象值 object objHeader = null; if (header != null) { fieldHeader = t.GetField(header.ClassName + "Value"); Type tHeader = assembly.GetType(nameSpace + "." + header.ClassName); objHeader = Activator.CreateInstance(tHeader); foreach (KeyValuePair <string, object> property in header.Properties) { FieldInfo[] arry1 = tHeader.GetFields(); int ts = arry1.Count(); FieldInfo f = tHeader.GetField(property.Key); if (f != null) { f.SetValue(objHeader, property.Value); } } } if (header != null) { //设置Soap头 fieldHeader.SetValue(obj, objHeader); } #endregion System.Reflection.MethodInfo mi = t.GetMethod(action); return(mi.Invoke(obj, args)); } }
public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?wsdl"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.ProtocolName = "Soap12"; sdi.Style = System.Web.Services.Description.ServiceDescriptionImportStyle.Client; //生成客户端代理。 sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; sdi.AddServiceDescription(sd, null, null); CodeNamespace cn = new CodeNamespace(@namespace); cn.Name = "WMS_JBS_Service"; //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CodeDomProvider provider = new CSharpCodeProvider();//设定编译参数 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 = provider.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)); } }
/* Given a URL, this method extracts the service type and the methods in the service */ /* The method and service type objects are returned to enable the caller to call the */ /* required service. */ private void GetWebServiceMethods(string url, out MethodInfo[] methodsInfo, out Type serviceType) { try { methodsInfo = null; serviceType = null; /* Create a new URI Object with the URL provided */ Uri uri = new Uri(url); /* Create a web request to the URI to obtain the WSDL file from the URI */ WebRequest webRequest = WebRequest.Create(uri); Stream wsdlRequestStream = webRequest.GetResponse().GetResponseStream(); ServiceDescription serviceDescription = ServiceDescription.Read(wsdlRequestStream); Service service = serviceDescription.Services[0]; string serviceDescriptionName = service.Name; /* Import service description to create a proxy for the methods present in */ /* the service. These proxies will later on be used to invoke each of those*/ /* services. */ ServiceDescriptionImporter servImport = new ServiceDescriptionImporter(); servImport.AddServiceDescription(serviceDescription, String.Empty, String.Empty); servImport.ProtocolName = "Soap"; servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; /* Create the compile unit and add the required namespaces to it. */ CodeNamespace nameSpace = new CodeNamespace(); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(nameSpace); /* Obtain the warnings from the compile unit */ ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit); /* If the warnings obtained are not empty, return */ if (warnings != 0) { return; } /* Create the string writer object to obtain the the Code DOM for the specified namespace */ StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture); CSharpCodeProvider prov = new CSharpCodeProvider(); prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions()); /* Set all the required parameters and perform a compilation */ 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 = prov.CompileAssemblyFromDom(param, codeCompileUnit); Assembly assembly = results.CompiledAssembly; serviceType = assembly.GetType(serviceDescriptionName); methodsInfo = serviceType.GetMethods(); } catch (Exception ec) { throw new Exception(ec.Message); } }
/// <summary> /// GetWsProxyType 获取目标Web服务对应的代理类型 /// </summary> /// <param name="wsUrl">目标Web服务的url</param> /// <param name="classname">Web服务的class名称,如果不需要指定,则传入null</param> public static Type GetWsProxyType(string wsUrl, string classname) { string @namespace = "ESBasic.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceHelper.GetWsClassName(wsUrl); } string cacheKey = wsUrl + "@" + classname; if (WebServiceHelper.WSProxyTypeDictionary.ContainsKey(cacheKey)) { return(WebServiceHelper.WSProxyTypeDictionary[cacheKey]); } //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(wsUrl + "?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[] ts = assembly.GetTypes(); Type wsProxyType = assembly.GetType(@namespace + "." + classname, true, true); lock (WebServiceHelper.WSProxyTypeDictionary) { if (!WebServiceHelper.WSProxyTypeDictionary.ContainsKey(cacheKey)) { WebServiceHelper.WSProxyTypeDictionary.Add(cacheKey, wsProxyType); } } return(wsProxyType); }
public void Parse() { UriBuilder uriBuilder = new UriBuilder(webserv.Url); uriBuilder.Query = "WSDL"; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri); webRequest.ContentType = "text/xml;charset=\"utf-8\""; webRequest.Method = "GET"; webRequest.Accept = "text/xml"; ServiceDescription serviceDescription; using (WebResponse response = webRequest.GetResponse()) { using (Stream stream = response.GetResponseStream()) { serviceDescription = ServiceDescription.Read(stream); } } var oldfuncs = (from q in new XPQuery <WebFunctions>(XpoDefault.Session) where q.Service.Oid == webserv.Oid select q).ToList(); if (serviceDescription != null && serviceDescription.Services.Count > 0) { ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = "Soap11"; importer.AddServiceDescription(serviceDescription, null, null); importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; Service service = serviceDescription.Services[0]; this.Namespace = serviceDescription.TargetNamespace; this.ServiceName = service.Name; webserv.ServiceName = service.Name; webserv.NameSpace = serviceDescription.TargetNamespace; webserv.UpdateDate = DateTime.Now; for (int i = webserv.SoapClasses.Count - 1; i >= 0; i--) { webserv.SoapClasses[i].Delete(); } #region Operation List <string> operationNames = new List <string>(); //Loop through the port types in the service description and list all of the //web service's operations and each operations input/output PortType portType = serviceDescription.PortTypes[0]; //foreach (PortType portType in serviceDescription.PortTypes) { int FunctionIndex = 0; this.Functions = new List <WebFunctions>(); foreach (Operation operation in portType.Operations) { WebFunctions newFunc = new WebFunctions(); newFunc.Service = webserv; var oldfunc = oldfuncs.Where(x => x.Name == operation.Name).FirstOrDefault(); if (oldfunc != null) { newFunc.Output = oldfunc.Output; } newFunc.Name = operation.Name; newFunc.SoapAction = this.Namespace + operation.Name; operationNames.Add(operation.Name); foreach (var message in operation.Messages) { if (message is OperationInput) { foreach (Message messagePart in serviceDescription.Messages) { if (messagePart.Name != ((OperationMessage)message).Message.Name) { continue; } foreach (MessagePart part in messagePart.Parts) { newFunc.InputType = part.Element.Name; } } } if (message is OperationOutput) { foreach (Message messagePart in serviceDescription.Messages) { if (messagePart.Name != ((OperationMessage)message).Message.Name) { continue; } foreach (MessagePart part in messagePart.Parts) { newFunc.OutputType = part.Element.Name; } } } } newFunc.Save(); this.Functions.Add(newFunc); FunctionIndex++; } } //End listing of types for (int i = oldfuncs.Count - 1; i >= 0; i--) { oldfuncs[i].Delete(); } #endregion #region Types Types types = serviceDescription.Types; XmlSchema xmlSchema = types.Schemas[0]; foreach (object item in xmlSchema.Items) { XmlSchemaComplexType _complexType = item as System.Xml.Schema.XmlSchemaComplexType; XmlSchemaElement schemaElement = item as XmlSchemaElement; XmlSchemaComplexType complexType = item as XmlSchemaComplexType; if (schemaElement != null && JavaTypeConverter.IsComplexType(schemaElement.Name)) { SoapClasses newClass = this.GetClass(schemaElement.Name); newClass.Name = schemaElement.Name; newClass.Service = webserv; newClass.Type = ClassType.Unknown; newClass.SuperClassType = string.Empty; newClass.Output = false; if (_complexType != null) { XmlSchemaContentModel model = _complexType.ContentModel; XmlSchemaComplexContent complex = model as XmlSchemaComplexContent; if (complex != null) { XmlSchemaComplexContentExtension extension = complex.Content as XmlSchemaComplexContentExtension; if (extension != null) { newClass.SuperClassType = extension.BaseTypeName.Name; } } } XmlSchemaType schemaType = schemaElement.SchemaType; XmlSchemaComplexType schemaComplexType = schemaType as XmlSchemaComplexType; if (schemaComplexType != null) { XmlSchemaParticle particle = schemaComplexType.Particle; XmlSchemaSequence sequence = particle as XmlSchemaSequence; if (sequence != null) { foreach (XmlSchemaElement childElement in sequence.Items) { SoapClassProperties newProp = new SoapClassProperties(XpoDefault.Session); newProp.Name = childElement.Name; newProp.PropertyClassType = childElement.SchemaTypeName.Name; newProp.IsArray = childElement.SchemaTypeName.Name.StartsWith("ArrayOf"); newClass.Properties.Add(newProp); } } } newClass.Save(); //this.ComplexTypes.Add(newClass); } else if (complexType != null) { OutputElements(complexType.Particle, complexType.Name); if (complexType.Particle == null) { GetProperties(xmlSchema, complexType.Name); } } } #region enums foreach (object xItem in xmlSchema.SchemaTypes.Values) { XmlSchemaSimpleType item2 = xItem as XmlSchemaSimpleType; if (item2 != null) { GetEnum(xmlSchema, item2.Name); } } #endregion #endregion } webserv.Save(); }
/// < summary> /// 动态调用web服务 /// < /summary> /// < param name="url">WSDL服务地址< /param> /// < param name="classname">类名< /param> /// < param name="methodname">方法名< /param> /// < param name="args">参数< /param> /// < returns>< /returns> public object InvokeWebService(string url, string classname, string methodname, object[] args) { //string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceHelper.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); if (!url.ToUpper().Contains("WSDL")) { url = string.Format("{0}?{1}", url, "WSDL"); } Stream stream = wc.OpenRead(url); 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 icc = new CSharpCodeProvider(); //设定编译参数 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)); /* * PropertyInfo propertyInfo = type.GetProperty(propertyname); * return propertyInfo.GetValue(obj, null); * */ } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public static int GetWebServiceDataWSDL(string url, string funcName, string className, Object[] parameters, ref Object retItem) { try { string @namespace = "KFBIO.Webservice.WSDL"; System.Net.WebClient client = new System.Net.WebClient(); //String classname; //String url = System.Configuration.ConfigurationManager.ConnectionStrings["serviceAddress"].ConnectionString;//这个地址可以写在Config文件里面,这里取出来就行了.在原地址后面加上: ?WSDL //String url = "http://192.168.4.4:8090/yfy-client/services/Msg_Service"; //String param = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><NOTICEMSG><MSGCONTENT><APPLICATION><INP_ID></INP_ID><INP_VISIT_TYPE_CD>1</INP_VISIT_TYPE_CD><NAME></NAME><GENDER_CD>2</GENDER_CD><BIRTHDATE> </BIRTHDATE><ID_NO></ID_NO><PATI_PHONE> </PATI_PHONE><PROVINCE_NAME> </PROVINCE_NAME><CITY_NAME> </CITY_NAME><AREA_NAME> </AREA_NAME><STREET_ID> </STREET_ID><VILLAGE_NAME> </VILLAGE_NAME><HOUSE_NO> </HOUSE_NO><APPLY_REASON>2</APPLY_REASON><CONSULT_AIM>远程诊断</CONSULT_AIM><ILLNESS_DIAG> </ILLNESS_DIAG><CONSULT_ORG_CODE> </CONSULT_ORG_CODE><CONSULT_ORG_NAME> </CONSULT_ORG_NAME></APPLICATION><EXAMSET><REPORT_NO> </REPORT_NO><REPORT_DATE> </REPORT_DATE><TEST_DEPT_NAME>病理科</TEST_DEPT_NAME><REPORT_DOC_NAME>牛爱芳</REPORT_DOC_NAME><ITEM_CD>00213564</ITEM_CD><ITEM_NAME>病理诊断</ITEM_NAME><CLINICDESC>送检目的</CLINICDESC><EXAMFINDING>检查所见</EXAMFINDING><EXAMCONCLUSION>检查结论</EXAMCONCLUSION><FTP_USER>FTP</FTP_USER><FTP_PASSWORD>1234</FTP_PASSWORD><FTP_FILEPATH> FTP文件完整路径</FTP_FILEPATH></EXAMSET></MSGCONTENT><CREATETIME>产生日期时间</CREATETIME></NOTICEMSG>"; //classname = "Msg_Service"; url = url + "?wsdl"; Stream stream = client.OpenRead(url); ServiceDescription description = ServiceDescription.Read(stream); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //创建客户端代理代理类。 importer.ProtocolName = "Soap"; //指定访问协议。 importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理。 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //添加WSDL文档。 CodeNamespace nmspace = new 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; if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("Temp"))) { Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("Temp")); } parameter.OutputAssembly = System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll"; //"D:/TempClass.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) { // 显示编译错误信息 //临时模板编译错误,内部错误 string a = System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll"; if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll")) { return(-5); } } System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(System.Web.HttpContext.Current.Server.MapPath("Temp/") + "TempClass.dll");//加载前面生成的程序集 //Type t = asm.GetType(nameSpace + "." + className); Type t = asm.GetType(@namespace + "." + className); object o = Activator.CreateInstance(t); System.Reflection.MethodInfo method = t.GetMethod(funcName);//CONSULTAPPLYNOTICE_PATHOLOGY是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下 retItem = method.Invoke(o, parameters); } catch (WebException ex) { //网络异常异常 return(-1); } catch (Exception ex) { //未知错误 return(-99); } return(0); }
private void DynamicInvocation(string wsUrl, TreeView tv, ref MethodInfo[] methodInfo) { try { Uri uri = new Uri(wsUrl); //txtUrl.Text); 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 TreeNode n = new TreeNode(sdName); tv.Nodes.Add(n); //treMethods.Nodes.Add(n); // 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()); // Compile the assembly with the appropriate references string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" }; CompilerParameters par = new CompilerParameters(assemblyReferences); par.GenerateExecutable = false; par.GenerateInMemory = true; par.TreatWarningsAsErrors = false; par.WarningLevel = 4; CompilerResults results = new CompilerResults(new TempFileCollection()); results = prov.CompileAssemblyFromDom(par, codeCompileUnit); Assembly assembly = results.CompiledAssembly; service = assembly.GetType(sdName); methodInfo = service.GetMethods(); foreach (MethodInfo t in methodInfo) { if (t.Name == "Discover") break; n = new TreeNode(t.Name); tv.Nodes[0].ChildNodes.Add(n); } tv.Nodes[0].Expand(); } else lblMsg.Text += warnings; } catch (Exception ex) { lblMsg.Text += "\r\n" + ex.Message + "\r\n\r\n" + ex.ToString(); ; } }
private int CreateServices(string wsdl_text) { Type service; try { //Try Database Connection SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SAASDB"].ToString()); try { conn.Open(); } catch (Exception e) { //Return Error return -1; } localhost.Service serviceObj = new localhost.Service(); //Insert into Data Table the services int count = 0; List<string> fieldnames = new List<string>(); List<localhost.Field> fieldlist = new List<localhost.Field>(); localhost.Field[] fields = serviceObj.ReadField(11, 30); fieldlist = new List<localhost.Field>(fields); foreach (localhost.Field item in fieldlist) { fieldnames.Add(count.ToString()); count++; } Uri uri = new Uri(wsdl_text); 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()); // 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); string input_params = ""; string return_type = ""; MethodInfo[] methodInfo = service.GetMethods(); foreach (MethodInfo t in methodInfo) { List<string> valueNames = new List<string>(); if (t.Name == "Discover") break; input_params = ""; return_type = ""; foreach (ParameterInfo parameter in t.GetParameters()) { //paramname.Text = "(" + temp.ParameterType.Name + " " + temp.Name + ")"; input_params = input_params + parameter.Name + ":" + parameter.ParameterType.Name + " "; } //Get The Return type of the Service(Method) return_type = t.ReturnType.ToString(); //Insert into Service Object(Methods Table) valueNames.Add(Session["OrgID"].ToString()); valueNames.Add(wsdl_text); valueNames.Add(t.Name); valueNames.Add(input_params); valueNames.Add(return_type); bool success = serviceObj.InsertData(11, 30, "WSDL-Instance", fieldnames.ToArray(), valueNames.ToArray()); if (success == false) { return -1; } } return 1; } else { return -1; } } catch (Exception ex) { return -1; } }