根据Webservice地址,动态传入参数(Webservice代理类)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sunlib;
using System.Net;
using System.IO;
using System.Web.Services.Description;
using System.CodeDom;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
public class Webservice
{
public static object InvokeWebService(string url , string methodName , object[] args)
{
string @namespace="client";
StringBuilder sb = new StringBuilder();
try
{
WebClient ws = new WebClient();
Stream stream=ws.OpenRead(url+"?WSDL");
ServiceDescription sd=ServiceDescription.Read(stream);
string classname=sd.Services[0].Name;
ServiceDescriptionImporter sdi=new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd,"","");
CodeNamespace cn=new CodeNamespace(@namespace);
CodeCompileUnit ccu= new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn,ccu);
CsharpCodeProvider csc=new CsharpCodeProvider();
//设定编译参数
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 cs =csc.CompileAssemblyFormDom(cplist,ccu);
if(cs.Errors.HasErrors)
{
foreach(CompilerError ce in cs.Errors)
{
sb.Append(ce.ToString()).AppendLine();
}
throw new Exception(sb.ToString());
}
Assembly assembly =cs.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 e)
{
sb.Append(e.Message).AppendLine();
return null;
}
finally
{
LogHelper.WriteTxt(sb.ToString());
}
}
}
public class UpdateData
{
public dynamic UpdateDatas(params string[] args)
{
//user用户名;pwd密码
string result=Webservice.InvokeWebService(WebServiceURL,MethodName,new object[]{ user,pwd,args[0],args[1],args[2],args[3] }).ToString();
//string result=Webservice.InvokeWebService(WebServiceURL,MethodName,new object[]{args }).ToString();
}
}
public class synsReadData
{
public void ReadData()
{
//
UpdateData updateData=new UpdateData();
dynamic rlt=updateData.UpdateDatas(userCode,meterCode,markTime,markData);
//dynamic rlt=updateData.UpdateDatas(result.ToString());//result为json数据
if(rlt==null)
{
sb.Append("WebService调用异常返回null").AppendLine();
continue;
}
//返回调用结果
string execCode=rlt.RetInfo.Code.ToString();
}
}