首页 > 技术文章 > 调用webservice帮助类

daimaxuejia 2019-04-04 15:27 原文

帮助类

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web.Services.Description;
using System.Xml.Serialization;

namespace DCZY.HookPlanIF
{
public class WSHelper
{
private static object _obj = new object();
private static WSHelper _ws = null;
private object _wsClassInstance = null;
private Type _wsClassType = null;

private string _nameSpace = string.Empty;
private string _className = string.Empty;
private string _wsUrl = string.Empty;

private bool _lastConn = true;
#region 事件
public event Action<bool> WsConnectionHandle;
#endregion

#region 单一实例
private WSHelper()
{
_nameSpace = ConfigurationManager.AppSettings["NameSpace"].ToString();//没什么用
_className = ConfigurationManager.AppSettings["ClassName"].ToString();//webservice名称
_wsUrl = ConfigurationManager.AppSettings["WsUrl"].ToString() + "?wsdl";//url
}

/// <summary>
/// 获取当前实例
/// </summary>
public static WSHelper CurrentInstance
{
get
{
if (_ws == null)
{
lock (_obj)
{
if (_ws == null)
{
_ws = new WSHelper();
}
}
}
return _ws;
}
}
#endregion

/// <summary>
/// 获取数据
/// </summary>
/// <param name="methodName"></param>
/// <param name="param"></param>
/// <returns></returns>
public object GetData(string methodName, object[] param)
{
try
{
if (_wsClassInstance == null || _wsClassType == null)
CreateClassInstance();

System.Reflection.MethodInfo method = _wsClassType.GetMethod(methodName);
object item = method.Invoke(_wsClassInstance, param);

if (_lastConn != true && null != WsConnectionHandle)
{
_lastConn = true;
WsConnectionHandle.BeginInvoke(false, null, null);
}
return item;
}
catch (Exception e)
{
if (_lastConn != false && null != WsConnectionHandle)
{
_lastConn = false;
WsConnectionHandle.BeginInvoke(false, null, null);
}

return null;
} 
}

private void CreateClassInstance()
{
try
{
// 1. 使用 WebClient 下载 WSDL 信息。
WebClient web = new WebClient();

Stream stream = web.OpenRead(_wsUrl);
// 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;
// 添加 WSDL 文档。
importer.AddServiceDescription(description, null, null);
// 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.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");

CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);

if (!result.Errors.HasErrors)
{
Assembly asm = result.CompiledAssembly;
_wsClassType = asm.GetType(_className);
_wsClassInstance = Activator.CreateInstance(_wsClassType);
}
}
catch (Exception e)
{
_wsClassInstance = null;
_wsClassType = null;
throw e;
}

}

#region IDisposable
private bool disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
}
disposed = true;
}
}
~WSHelper()
{
Dispose(false);
}
#endregion
}
}

代码调用

using DCZY.Bean;
using DCZY.HookPlanIF;
using DCZY.HookPlanWS;
using PLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace DCZY.Server.WS
{
    public class WebServiceProxy
    {
        public WebServiceProxy()
        {

        }public static UserInfo setquestion(string questioninfo)
        {
            try
            {
                object[] obj = new object[1];
                obj[0] = questioninfo;
                object o = WSHelper.CurrentInstance.GetData("setquestion", obj);
                if (o == null)
                {
                    return null;
                }
                string strjson = o.ToString();
  
                //ResultInfoWS info = PTool.Ajax.JsonSerializer.Deserializer(strjson, typeof(ResultInfoWS)) as ResultInfoWS;
                return null;
            }
            catch (Exception e)
            {
                Log.WriteError(e.Message);
                return null;
            }
        }


        public static List<ClassPlanInfo> GetClassInfo(DateTime dtstart,DateTime dtend,string org,string type)
        {
            try
            {
                object[] obj = new object[4];
                obj[0] = dtstart.ToString("yyyy-MM-dd HH:mm:ss");
                obj[1] = dtend.ToString("yyyy-MM-dd HH:mm:ss");
                obj[2] = org;
                obj[3] = type;
                object o = WSHelper.CurrentInstance.GetData("GroupInfoAccess", obj);
                if (o == null)
                {
                    return null;
                }
                string strjson = o.ToString();

                ResultInfoWS<List<ClassInfoWS>> info = PTool.Ajax.JsonSerializer.Deserializer(strjson, typeof(ResultInfoWS<List<ClassInfoWS>>)) as ResultInfoWS<List<ClassInfoWS>>;
                if (info == null)
                {
                    return null;
                }
                if (info.data == null || info.data.Count == 0)
                {
                    return null;
                }
                List<ClassPlanInfo> cpinfo = new List<ClassPlanInfo>();
                foreach (ClassInfoWS item in info.data)
                {
                    cpinfo.Add(item.ToClassGroup());
                }
                return cpinfo;
            }
            catch (Exception e)
            {
                Log.WriteError(e.Message);
                return null;
            }
        }

        public static OtherRiskWs<Datum> GetOtherRiskInfo(string BeginDate, string EndDate, string rskID = "")
        {
            object[] obj = new object[3];
            obj[0] = BeginDate;
            obj[1] = EndDate;
            obj[2] = rskID;
            object o= WSHelper.CurrentInstance.GetData("WorkRisk", obj);
            if (o == null)
            {
                return null;
            }
            string strjson = o.ToString();
            OtherRiskWs<Datum> info = PTool.Ajax.JsonSerializer.Deserializer(strjson, typeof(OtherRiskWs<Datum>)) as OtherRiskWs<Datum>;
            if (info == null)
            {
                return null;
            }
            if (info.data == null)
            {
                return null;
            }
            return info;
        }

        public static OtherRiskWs<WorkSee> GetWorkSeeInfo(string Date, string sta_name = "")
        {
            object[] obj = new object[2];
            obj[0] = Date;
            obj[1] = sta_name;
            object o = WSHelper.CurrentInstance.GetData("WhatchSee", obj);
            if (o == null)
            {
                return null;
            }
            string strjson = o.ToString();
            OtherRiskWs<WorkSee> info = PTool.Ajax.JsonSerializer.Deserializer(strjson, typeof(OtherRiskWs<WorkSee>)) as OtherRiskWs<WorkSee>;
            if (info == null)
            {
                return null;
            }
            if (info.data == null)
            {
                return null;
            }
            return info;
        }
    }
}

配置文件

 <add key="WsUrl" value="http://192.168.2.247:8054/HookPlanService.asmx" />
    <add key="NameSpace" value="http://tempuri.org/" />
    <add key="ClassName" value="HookPlanService" />

 

推荐阅读