码迷,mamicode.com
首页 > 其他好文 > 详细

WCF创建到使用

时间:2016-04-05 13:56:13      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

1,在VS里面新建一个类库项目

技术分享

2,向类库项目里添加WCF服务文件

技术分享

3.按照WCF约束规范编写接口和实现类

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfDataSreve
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IOracleServe”。
    [ServiceContract]
    [ServiceKnownType(typeof(DBNull))]
    public interface IOracleServe
    {
        [OperationContract]
        DataTable GetOrderHandleData(string orderindex);
        [OperationContract]
        DataTable GetWorkOrderData(string orderindex);
        [OperationContract]
        DataTable GetWorkOrderByDate(string starttime, string endtime);
        [OperationContract]
        string DeleteOrderHandle(string orderindex);
        [OperationContract]
        string DeleteAllOrderHandle(string orderindex);
        [OperationContract]
        string StrConn(string index);

        
    }
}

  

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfDataSreve
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“OracleServe”。
   
    public class OracleServe : IOracleServe
    {
        public string ConnectionString { get; set; }
        public OracleServe()
          {
             ConnectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
          }
        public DataTable GetOrderHandleData(string orderindex)
         {
             using ( OracleConnection conn = new OracleConnection(ConnectionString))
             {
                
                 conn.Open();
                 OracleCommand cmd = new OracleCommand();
                 cmd.CommandText = @"select * from M_ORDERHANDLE where ORDERINDEX  = ‘" + orderindex + "‘";  
                 cmd.Connection = conn;
                 cmd.CommandType = CommandType.Text;
                 OracleDataAdapter da = new OracleDataAdapter(cmd);
                 DataSet ds = new DataSet();
                 da.Fill(ds,"OrderHandle");
                 conn.Close();
                 return ds.Tables["OrderHandle"];
             }    
         }
       public  DataTable GetWorkOrderData(string orderindex)
         {
             using (OracleConnection conn = new OracleConnection(ConnectionString))
             {
                
                 conn.Open();
                 OracleCommand cmd = new OracleCommand();
                 cmd.Connection = conn;
                 cmd.CommandText = @"SELECT * FROM M_WORKORDER where ORDERINDEX  = ‘" + orderindex + "‘";  
                 cmd.CommandType = CommandType.Text;
                 OracleDataAdapter da = new OracleDataAdapter(cmd);
                 DataSet ds = new DataSet();
                 da.Fill(ds, "WorkOrder");
                 return ds.Tables["WorkOrder"];
                 
             }
         }
      public DataTable GetWorkOrderByDate(string starttime, string  endtime )
       {
           using (OracleConnection conn = new OracleConnection(ConnectionString))
           {
                
               conn.Open();
               OracleCommand cmd = new OracleCommand();
               cmd.Connection = conn;
               cmd.CommandText = @"SELECT * FROM M_WORKORDER where to_char(CREATETIME, ‘yyyy-mm-dd‘) >= ‘" + Convert.ToDateTime(starttime).ToString("yyyy-MM-dd") + "‘ and to_char(CREATETIME, ‘yyyy-mm-dd‘) <= ‘" + Convert.ToDateTime(endtime).ToString("yyyy-MM-dd") + "‘";
               cmd.CommandType = CommandType.Text;
               OracleDataAdapter da = new OracleDataAdapter(cmd);
               DataSet ds = new DataSet();
               da.Fill(ds, "WorkOrder");
               return ds.Tables["WorkOrder"];

           }
       }
       public string StrConn(string index)
       {
           return ConnectionString+index;
       }
       public string DeleteOrderHandle(string orderindex)
       {
          
              using (OracleConnection conn = new OracleConnection(ConnectionString))
             {
                 conn.Open();
                 OracleCommand cmd = new OracleCommand();
                 cmd.Connection = conn;
                 cmd.CommandText = @"Delete  FROM M_ORDERHANDLE where HANDLELSH  = ‘" + orderindex + "‘";  
                 cmd.CommandType = CommandType.Text;
                 if(cmd.ExecuteNonQuery()>0)
                 {
                     return "OK";
                 }
                 else
                 {
                     return "No";
                 }
                 
             }
       }

       public string DeleteAllOrderHandle(string orderindex)
      {
          using (OracleConnection conn = new OracleConnection(ConnectionString))
          {
              conn.Open();
              OracleCommand cmd = new OracleCommand();
              cmd.Connection = conn;
              cmd.CommandText = @"Delete  FROM M_ORDERHANDLE where ORDERINDEX = ‘" + orderindex + "‘";
              cmd.CommandType = CommandType.Text;
              if (cmd.ExecuteNonQuery() > 0)
              {
                  return "OK";
              }
              else
              {
                  return "No";
              }

          }
      }
    }
}

  

ConnectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];此句读取下面创建的WCF服务中web.config的节点

4,右击解决方案添加新建网站-》WCF服务

技术分享

技术分享

5,更改网站信息,web.config,添加数据库访问路径节点(加粗部分)

 <?xml version="1.0" ?> 
- <configuration>
- <system.web>
  <compilation debug="true" targetFramework="4.0" /> 
  </system.web>
- <system.serviceModel>
- <services>
- <service name="WcfDataSreve.OracleServe">
  <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="LargeDataTransferServicesBinding" contract="WcfDataSreve.IOracleServe" /> 
  </service>
  </services>
- <bindings>
- <basicHttpBinding>
- <binding name="LargeDataTransferServicesBinding" maxReceivedMessageSize="2147483647" messageEncoding="Text" transferMode="Streamed" sendTimeout="00:10:00">
  <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
  </binding>
  </basicHttpBinding>
  </bindings>
- <behaviors>
- <serviceBehaviors>
- <behavior>
- <!--  为避免泄漏元数据信息,请在部署前将以下值设置为 false 
  --> 
  <serviceMetadata httpGetEnabled="true" /> 
- <!--  要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 
  --> 
  <serviceDebug includeExceptionDetailInFaults="false" /> 
  </behavior>
  </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
  </system.serviceModel>
- <system.webServer>
  <modules runAllManagedModulesForAllRequests="true" /> 
- <!--         若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
        在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
      
  --> 
  <directoryBrowse enabled="true" /> 
  </system.webServer>
- <appSettings>
  <add key="ConnectionString" value="Data Source=10.192.165.144/OSMP;User ID=cnosm;Password=osm1234$" /> 
  </appSettings>
  </configuration>

6,更改WCF服务下的Service.svc文件,并把App_Code文件夹下的系统定义的服务删除

<%@ ServiceHost Language="C#" Debug="true" Service="WcfDataSreve.OracleServe" >

              加粗部分为类库名.服务实现类

7,当传输数据量大或是需要控制传输量时添加红色部分代码

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfDataSreve.OracleServe">
        <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="LargeDataTransferServicesBinding" contract="WcfDataSreve.IOracleServe"/>
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="LargeDataTransferServicesBinding" maxReceivedMessageSize="2147483647"
                 messageEncoding="Text" transferMode="Streamed" sendTimeout="00:10:00" >
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2147483647"
              maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
        在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
  <appSettings>
    <add key="ConnectionString" value="Data Source=10.192.165.144/OSMP;User ID=cnosm;Password=osm1234$"/>
  </appSettings>
</configuration>

7,右击解决方案创建WPF程序引用上面的服务

 在WPF项目中右击引用-》添加服务引用-》打开页面点击发现,确认即可,

引用方法是,服务引用名.服务实现类名Client new wcf=服务引用名.服务实现类名Client();即可通过对象名引用服务接口(部分代码)

 public class DataViewModel: ViewModelBase
    {
        public ObservableCollection<OrderHandle> OrderHandleList{get; set;}
        public WCFOracleService.OracleServeClient Wcf;
        public DataViewModel()
        {
            OrderHandleList = new ObservableCollection<OrderHandle>();
            Wcf = new WCFOracleService.OracleServeClient();
            DeleteSelect = new RelayCommand(ExecuteSelect, CanExecuteSelect);
            DeleteAll = new RelayCommand(ExecuteAllDelete, CanExecuteALl);
        }
        public void QueryOrderHandle(string orderindex)
        {
            DataTable table = Wcf.GetOrderHandleData(orderindex);
            if(table==null)
            {
                return;
            }
            for(int i=0;i<table.Rows.Count;i++)
            {
                OrderHandle Oh = new OrderHandle();
                Oh.HandleDescrtption = table.Rows[i]["HANDLEDESCRIPTION"].ToString();
                Oh.HandLelsh = table.Rows[i]["HANDLELSH"].ToString();
                Oh.OrderIndex = table.Rows[i]["ORDERINDEX"].ToString();
                Oh.HandlePerson = table.Rows[i]["HANDLEPERSON"].ToString();
                Oh.HandLetype = table.Rows[i]["HANDLETYPE"].ToString();
                Oh.HandleTime =table.Rows[i]["HANDLETIME"].ToString();
                Oh.HandleStatus = table.Rows[i]["HANDLESTATUS"].ToString();
                Oh.Select = false;
                OrderHandleList.Add(Oh);
            }
        }

  8 发布至IIS

      (1).把整个WCF服务文件拷贝至服务器中

      技术分享

(2)找到服务器中IIS管理器找到网站,新添加一个网站,配置基本信息,

技术分享

(3)配置完成后,点击IIS右侧浏览网站-》点击Service.svc,拷贝如下地址到添加服务引用的页面即可找到,并引用

 

svcutil.exe http://IP地址和端口号
/Service.svc?wsdl

  

WCF创建到使用

标签:

原文地址:http://www.cnblogs.com/wangboke/p/5354635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!