2015年5月17日 星期日

WCF 簡易教學

公司希望有WCF當中介程式,隔離資料庫,這對習慣Web API的我們,有點對WCF生疏,所以寫了些簡單的教學,一方面怕自己有點生疏,另一方面給有需要的朋友們,減少學習的時間。

一、建立介面的宣告

在介面函式上輸入關鍵字『OperationContract』,這樣端點的服務
能搜尋到此宣告的函式,另外如果需要宣告物件時,該類別要宣告關鍵字『DataContract』,類別的屬性宣告『DataMember

 [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        IEnumerable<tempCalendar> readGoogleData(int intStartIkey, int intEndIkey);
        [OperationContract]
        bool writeGoogleData(tempCalendar updateData);
    }

[DataContract]
    public class tempCalendar
    {
        [DataMember]
        public int ikey
        {
            get;
            set;
        }
        [DataMember]
        public string sendParameter
        {
            get;
            set;
        }     
    }

二、  實作介面的類別

用EntitySQL linq語法去讀取資料庫的資料和寫入資料庫的資料,直接
回傳IEnumerable型別,就因為取回的資料只是用來查詢, 會有較佳的執行速度

public class Service1 : IService1
    {
        GoogleEntities googleEntityObj = new GoogleEntities();
        public IEnumerable<tempCalendar> readGoogleData(int intStartIkey, int intEndIkey)
        {
                IEnumerable<tempCalendar> tempCalendarList = from c in googleEntityObj.Calendar
                     Where  c.ikey >= intStartIkey && c.ikey <= intEndIkey
                                       select new tempCalendar
                                          {
                                             ikey=c.ikey,
                                              sendParameter=c.上傳參數
                                          };
                return tempCalendarList;
        }

        public bool writeGoogleData(tempCalendar updateData)
        {
                var original = googleEntityObj.Calendar.Find(updateData.ikey);
                original.上傳完成 = updateData.isSendGoogleOK;
                original.結果訊息 = updateData.sendMessage;;
                googleEntityObj.SaveChanges();
                return true;
        }
    }


三、  設定web.config
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
<!--預設允許大量傳輸 -->
        <binding name="cusBinding" maxBufferSize="64000000" maxReceivedMessageSize="64000000"   />
      </basicHttpBinding>
    </bindings>
    <client>
<!--連線端口設為basicHttpBinding 具名管線,  -->
      <endpoint binding="basicHttpBinding" bindingConfiguration="cusBinding" contract="WcfService1.IService1"/>
    </client>
    <services>
      <service name="WcfService1.Service1" >
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="cusBinding" contract="WcfService1.IService1" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
<!--預設連線數允許到100 -->
          <serviceThrottling maxConcurrentCalls="100" maxConcurrentSessions="50" maxConcurrentInstances="50" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>

四、  如何呼叫service

先透過vs2012tool 視窗,執行svcutil.exe  service.svc的位址,自
動產生檔案到 c:\programe(X86)\ Microsoft Visual Studio 12.0, 2個檔案加入到呼叫service的程式專案

















以下示範如何呼叫服務

  public IEnumerable<tempCalendar> serviceReadGoogleData(int intStartIkey, int intEndIkey)
        {
            try
            {
                BasicHttpBinding myBinding = new BasicHttpBinding();
                EndpointAddress myEndpoint = new EndpointAddress("http://192.168.1.63/googleService/service1.svc");
                ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>(myBinding, myEndpoint);
                IService1 wcfClient1 = myChannelFactory.CreateChannel();
               return wcfClient1.readGoogleData(intStartIkey, intEndIkey);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
五、  設定web協定

服務的介面要改成GETPOST等協定,可以依自己的習慣修改網址的傳遞
參數的模式

IService.svc
    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "writeToGoogleCalendar/orgIkey/{orgIkey}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    bool writeToGoogleCalendar(string orgIkey);

Service.svc.cs
public bool writeToGoogleCalendar(string orgIkey)
        {
            return true;
        }


修改Web.config
<system.serviceModel>
    <bindings>
    </bindings>
    <client>
      <endpoint binding="webHttpBinding" bindingConfiguration="" contract="WcfService1.IService1" />
    </client>
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding"
          bindingConfiguration="" contract="WcfService1.IService1" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <serviceThrottling maxConcurrentCalls="100" maxConcurrentSessions="50"
            maxConcurrentInstances="50" />
        </behavior>
      </serviceBehaviors>
    </behaviors>


呼叫WCF網址:




六、  參考文獻

1.    https://social.msdn.microsoft.com/Forums/vstudio/en-US/2df5458f-3b83-4fb7-9761-bb6d359450a7/wcf-client-connection-limits-?forum=wcf

沒有留言:

張貼留言