object CreateWebServiceFromWsdl(byte[] wsdl) { // generate CodeDom from WSDL ServiceDescription sd = ServiceDescription.Read(new MemoryStream(wsdl)); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ServiceDescriptions.Add(sd); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(""); codeCompileUnit.Namespaces.Add(codeNamespace); importer.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync; importer.Import(codeNamespace, codeCompileUnit); // update web service proxy CodeDom tree to add dynamic support string wsProxyTypeName = FindProxyTypeAndAugmentCodeDom(codeNamespace); // compile CodeDom tree into an Assembly CodeDomProvider provider = CodeDomProvider.CreateProvider("CS"); CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add(typeof(Ops).Assembly.Location); //DLR CompilerResults results = provider.CompileAssemblyFromDom(compilerParams, codeCompileUnit); Assembly generatedAssembly = results.CompiledAssembly; // find the type derived from SoapHttpClientProtocol Type wsProxyType = generatedAssembly.GetType(wsProxyTypeName); if (wsProxyType == null) { throw new InvalidOperationException("Web service proxy type not generated."); } // create an instance of the web proxy type return Activator.CreateInstance(wsProxyType); }
CodeNamespace GenerateCodeFromWsdl(ServiceDescription sd) { ServiceDescriptionImporter imp = new ServiceDescriptionImporter(); imp.AddServiceDescription(sd, null, null); CodeNamespace cns = new CodeNamespace(); imp.Import(cns, null); return(cns); }
/// <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)); }
public void GenerateWebReferencesEmpty() { // yuck - This causes NRE. //ServiceDescriptionImporter.GenerateWebReferences ( // new WebReferenceCollection (), null, null, null); ServiceDescriptionImporter.GenerateWebReferences( new WebReferenceCollection(), null, new CodeCompileUnit(), new WebReferenceOptions()); }
/// <summary> /// Builds an assembly from a web service description. /// The assembly can be used to execute the web service methods. /// </summary> /// <param name="webServiceUri">Location of WSDL.</param> /// <returns>A web service assembly.</returns> private Assembly BuildAssemblyFromWSDL(Uri webServiceUri) { if (String.IsNullOrEmpty(webServiceUri.ToString())) { throw new Exception("Web Service Not Found"); } ServiceDescriptionImporter descriptionImporter = BuildServiceDescriptionImporter(webServiceUri.ToString() + "?wsdl"); return(CompileAssembly(descriptionImporter)); }
public static object InvokeWebService(string url, string classname, string methodname, object[] args) { object obj3; string name = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = GetWsClassName(url); } try { WebClient client = new WebClient(); ServiceDescription serviceDescription = ServiceDescription.Read(client.OpenRead(url + "?WSDL")); ServiceDescriptionImporter importer = new ServiceDescriptionImporter { ProtocolName = "Soap", Style = ServiceDescriptionImportStyle.Client, CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties }; importer.AddServiceDescription(serviceDescription, "", ""); CodeNamespace namespace2 = new CodeNamespace(name); 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) { StringBuilder builder = new StringBuilder(); foreach (CompilerError error in results.Errors) { builder.Append(error.ToString()); builder.Append(Environment.NewLine); } throw new Exception(builder.ToString()); } Type type = results.CompiledAssembly.GetType(name + "." + classname, true, true); object obj2 = Activator.CreateInstance(type); obj3 = type.GetMethod(methodname).Invoke(obj2, args); } catch (Exception exception) { throw new Exception(exception.InnerException.Message, new Exception(exception.InnerException.StackTrace)); } return(obj3); }
private IotMService() { string serviceUrl = System.Configuration.ConfigurationManager.AppSettings["IotMServiceUrl"]; // 1. 使用 WebClient 下载 WSDL 信息。 WebClient web = new WebClient(); Stream stream = web.OpenRead(serviceUrl); // 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 = "IotMService.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) { // 显示编译错误信息 } asm = Assembly.LoadFrom("IotMService.dll"); t = asm.GetType("OlbService"); }
/// <summary> /// Builds an assembly from a web service description. /// The assembly can be used to execute the web service methods. /// </summary> /// <param name="webServiceUri">Location of WSDL.</param> /// <returns> /// A web service assembly. /// </returns> /// <exception cref="System.Exception">Web Service Not Found</exception> private Assembly BuildAssemblyFromWSDL(Uri webServiceUri) { if (String.IsNullOrEmpty(webServiceUri.ToString())) { throw new Exception(ErrorResource.WebServiceNotFound); } using (var xmlreader = new XmlTextReader(webServiceUri + "?wsdl")) { ServiceDescriptionImporter descriptionImporter = BuildServiceDescriptionImporter(xmlreader); return(CompileAssembly(descriptionImporter)); } }
/// <summary> /// /// </summary> /// <returns></returns> private CodeCompileUnit GenerateCSharpFile() { //编译工作单元 CodeCompileUnit ccu = new CodeCompileUnit(); //命名空间 CodeNamespace cn = new CodeNamespace("TestWebService"); ccu.Namespaces.Add(cn); ServiceDescriptionImporter sdi = DownLoadSoap(); sdi.Import(cn, ccu); return(ccu); }
/// <summary< /// 设置代理 /// </summary< /// <param name="url"<</param< public static void SetWebServiceAgent(string url) { XmlTextReader reader = new XmlTextReader(url + "?wsdl"); //创建和格式化 WSDL 文档 ServiceDescription sd = ServiceDescription.Read(reader); //创建客户端代理代理类 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, null, null); //使用 CodeDom 编译客户端代理类 CodeNamespace cn = new CodeNamespace(CODE_NAMESPACE); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; //cp.OutputAssembly = "temp.dll";//输出程序集的名称 cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.XML.dll"); cp.ReferencedAssemblies.Add("System.Web.Services.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults cr = icc.CompileAssemblyFromDom(cp, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例 string key = url.ToLower(); Type agentType = cr.CompiledAssembly.GetTypes()[0]; //编译生成程序集Type _agentType.Add(key, agentType); object agent = Activator.CreateInstance(agentType); //生成代理实例 _agent.Add(key, agent); }
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 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; } }
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)); } }
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; } }