fumingxia 发表于 2015-8-13 07:38:01

基於IIS的WCF的分布式多層架構開發實現

曾用.NETRemoting,基於IIS,為公司實現過分布式多層架構,客戶端采用Web Browser瀏覽,當時,公司領導告訴我可能會有多臺中間服務器用於系統,又不想每臺電腦的去安裝程序,所以,我最后采用了.NET Remtoing來實現分布式,可直到如今,我也沒有看到有購置多臺中間服務器,哪怕多臺Web服務器的可能性。不過,功能咱是實現了,只要有了機器,俺就用上。先不管他,上博客園來看看,這一看,就看到张逸和 赵颉兩位牛人的“你知道什么是WCF嗎”的訪談錄,看完之后,對於WCF也就躍躍欲試,於是結合张逸以及博客园另一位牛人artech(都是MVP,羨慕中…..)介紹的內容, 加上本人對於Remoting的開發也有一點功底,於是也就沒有花多少時間,鼓搗出以下這個自己號稱目前最先進的基於IIS的WCF的分布式多層開發架構。
至於WCF的相關知識,咱也不說什么,张逸和Artech這兩位牛人說得已經很是明白了,各位可以通過上面的鏈接去他們的博客上學習啦,不過,感覺有Remoting開發經驗的,對於WCF的相關概念應該不是很難理解。
下面還是用代碼來說明一下(由於這家公司的經理要求使用VB來做,我只好放棄用了近兩年的C#的而改用VB了。還好現在基本上兩種都不會混了,也算是間接的掌握了一門新語言吧,喜歡看C#的朋友就請多擔待,或者留言,本人考盧是否提供一份C#的實現。呵呵:))
1、首先從整體來看這個架構,這個架構的圖示大約如下,共包括了6個專案,大概從專案名稱應該也可看出其主要用途了:


HL.EntityReflect.Osp專案實現是實體對象化。HL.Shared.Osp就是WCF的Contract了,於了Remoting來說,就是一個建議在Server端實現的接口了,其實為了安全性著想,對於WCF,本人也建議使用接口,在Server端實現。HL.Business.Osp就是我們常說的邏輯業務層,它主要負責調用HL.DALSQLServer.Osp真正實現了HL.Shared.Osp的方法。最后兩個HL.Service和HL.Win不用我說,各位也可想到一個是IIS Host的WCF及客戶端的Winform程序了。
上面簡單介紹了各個專案的用途了,下面我們來分步用VB實現:
2、建立實體對象:

EREmployee
Imports System
Imports System.Runtime.Serialization

'/ <summary>
'/ Summary description for EREmployee.
'/ </summary>
<Serializable()> _
<DataContract()> _
Public Class EREmployeeClass EREmployee
    Public Sub New()Sub New()
    End Sub
    Private _strbs_no As String
    Private _strbs_name As String

    <DataMember()> _
    Public Property strBS_NO()Property strBS_NO() As String
      Get
            Return Me._strbs_no
      End Get
      Set(ByVal value As String)
            Me._strbs_no = value
      End Set
    End Property

    <DataMember()> _
    Public Property strBS_NAME()Property strBS_NAME() As String
      Get
            Return Me._strbs_name
      End Get
      Set(ByVal value As String)
            Me._strbs_name = value
      End Set
    End Property
End Class
這個基於工具也可產生,網上大把。只是要註意的是,要能在WCF中傳遞的實體,必須是可序列化和序列化了的實體,在Remoting中我們需要在類前面冠上<Serializable()> _這種形式的編程即可,同樣在WCF中我們使用的是<DataContract()> _,然后在屬性前面也加上<DataMember()> _聲明。
3、同樣,我們再接著建立一個Contract,引用第二步建立的實體對象。我們使用類似下面的代碼,這里同樣運用了聲明式的編程方式。各位可以自行比較這些代碼跟我們常用的代碼的寫法的差異。

IEmployee
Imports System
Imports System.ServiceModel
Imports HL.EntityReflect.Osp

'/ <summary>
'/ Summary description for IEmployee.
'/ </summary>
<CLSCompliant(False)> _
<ServiceContract()> _
Public Interface IEmployeeInterface IEmployee
    <OperationContract()> _
    Function Query()Function Query() As EREmployee()

    <OperationContract()> _
    Sub Add()Sub Add(ByVal er As EREmployee)

    <OperationContract()> _
    Sub Modify()Sub Modify(ByVal er As EREmployee, ByVal strBS_NO As String, ByVal strBS_Name As String)

    <OperationContract()> _
    Sub Del()Sub Del(ByVal er As EREmployee)

    <OperationContract()> _
    Function fAdd()Function fAdd(ByVal intX As Integer, ByVal intY As Integer) As Integer
End Interface



4、這一步實現很關鍵,能否使用WCF成功,這一步至關重要,我們把對應的類繼承於ClientBase,並實現了HL.Shared.Osp,當然真實方法我們在另一個專案中實現,這里算是一個引子吧,權當我曾經好像看過某位牛人(如果沒有記錯應該也是上面張先生寫的一篇文章。關於Remoting的)說的.net下Remoting的欺騙吧。你把他當做欺騙也好,什么也好,只是我需要指明的是這個很重要,代碼如下:

BLEmployee
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports HL.EntityReflect.Osp
Imports HL.Shared.Osp
Imports System.Data.SqlClient


Public Class BLEmployeeClass BLEmployee
    Inherits ClientBase(Of IEmployee)
    Implements IEmployee

    Public Sub New()Sub New()
      MyBase.New()
    End Sub

    Public Sub New()Sub New(ByVal endpointConfigurationName As String)
      MyBase.New(endpointConfigurationName)
    End Sub

    Public Sub Add()Sub Add(ByVal er As EREmployee) Implements IEmployee.Add
      Channel.Add(er)
    End Sub

    Public Sub Del()Sub Del(ByVal er As EREmployee) Implements IEmployee.Del
      Channel.Del(er)
    End Sub

    Public Sub Modify()Sub Modify(ByVal er As EREmployee, ByVal strBS_NO As String, ByVal strBS_Name As String) Implements IEmployee.Modify
      Channel.Modify(er, strBS_NO, strBS_Name)
    End Sub

    Public Function Query()Function Query() As EREmployee() Implements IEmployee.Query
      Return Channel.Query()
    End Function


    Public Function fAdd()Function fAdd(ByVal intX As Integer, ByVal intY As Integer) As Integer Implements IEmployee.fAdd
      Return Channel.fAdd(intX, intY)
    End Function
End Class


當然,如果我想實現數據庫類型的切換,我以前用Remoting的時候,就在這個類中做手腳,但關於WCF卻感覺無從下手,如果哪位知道,請留言指教,不勝感激。
5、收尾一下4步中遺留的真正實現方法,不多說,直接看代碼:

SQLDaoEmployee
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports HL.EntityReflect.Osp
Imports HL.Shared.Osp

Public Class SQLDaoEmployeeClass SQLDaoEmployee
    Implements IEmployee

    Public ReadOnly Property strConn()Property strConn() As String
      Get
            Return Configuration.ConfigurationManager.AppSettings("strConnectNorthWind")
      End Get
    End Property

    Public Sub Add()Sub Add(ByVal er As EREmployee) Implements IEmployee.Add
      Dim strSql As String = "Insert Into Employee(BS_NO,BS_NAME) Values(@BS_NO,@BS_NAME)"
      Using Conn As New SqlConnection(strConn)
            Using Comm As New SqlCommand(strSql, Conn)
                Comm.Parameters.Add(New SqlParameter("@BS_NO", SqlDbType.VarChar, 10))
                Comm.Parameters.Add(New SqlParameter("@BS_NAME", SqlDbType.VarChar, 20))
                Comm.Parameters("@BS_NO").Value = er.strBS_NO
                Comm.Parameters("@BS_NAME").Value = er.strBS_NAME
                Conn.Open()
                Comm.ExecuteNonQuery()
                Conn.Close()
            End Using
      End Using
    End Sub

    Public Sub Del()Sub Del(ByVal er As EREmployee) Implements IEmployee.Del
      Dim strSql As String = "Delete fromEmployee where BS_NO ='" & er.strBS_NO & "' and BS_NAME='" & er.strBS_NAME & "'"
      Using Conn As New SqlConnection(strConn)
            Using Comm As New SqlCommand(strSql, Conn)
                Conn.Open()
                Comm.ExecuteNonQuery()
                Conn.Close()
            End Using
      End Using
    End Sub

    Public Sub Modify()Sub Modify(ByVal er As EREmployee, ByVal strBS_NO As String, ByVal strBS_Name As String) Implements IEmployee.Modify
      Dim strSql As String = "updateEmployee set BS_NO='" & strBS_NO & "', BS_NAME= '" & strBS_Name & _
                               "' where BS_NO ='" & er.strBS_NO & "' and BS_NAME='" & er.strBS_NAME & "'"
      Using Conn As New SqlConnection(strConn)
            Using Comm As New SqlCommand(strSql, Conn)
                Conn.Open()
                Comm.ExecuteNonQuery()
                Conn.Close()
            End Using
      End Using

    End Sub

    Public Function Query()Function Query() As EREmployee() Implements IEmployee.Query
      Dim lst As New List(Of EREmployee)()
      Dim strSql As String = "Select * From Employee"
      Using Conn As New SqlConnection(strConn)
            Using Comm As New SqlCommand(strSql, Conn)
                Conn.Open()
                Dim Reader As SqlDataReader = Comm.ExecuteReader()
                While Reader.Read()
                  Dim er As New EREmployee()
                  er.strBS_NO = DirectCast(Reader("BS_NO"), String)
                  er.strBS_NAME = DirectCast(Reader("BS_NAME"), String)
                  lst.Add(er)
                End While
                Conn.Close()
            End Using
      End Using
      Return lst.ToArray()
    End Function


    Public Function fAdd()Function fAdd(ByVal intX As Integer, ByVal intY As Integer) As Integer Implements IEmployee.fAdd
      Return intX + intY
    End Function

End Class


6、至此我們,可以開始配置,基於IIS的WCF服務端了。請看配置文件

WCF Service
<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>

    <configSections>
      <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
            <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
            <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
            <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
          </sectionGroup>
      </sectionGroup>
      </sectionGroup>
    </configSections>

<system.serviceModel>
    <services>
      <service name="HL.DALSQLServer.Osp.SQLDaoEmployee" behaviorConfiguration="ServiceBehavior">
      <!-- Service Endpoints -->
      <endpoint address="" binding="basicHttpBinding" contract="HL.Shared.Osp.IEmployee">
          <!--
            Upon deployment, the following identity element should be removed or replaced to reflect the
            identity under which the deployed service runs.If removed, WCF will infer an appropriate identity
            automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
      <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
      </serviceBehaviors>
    </behaviors>
</system.serviceModel>

<appSettings>
    <add key ="strConnectNorthWind" value ="Data Source=dg;Initial Catalog=Northwind;User ID=sa;Password="/>
</appSettings>
    <connectionStrings/>

    <system.web>
      <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.

            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
      -->
      <compilation debug="false" strict="false" explicit="true">

          <assemblies>
            <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
          </assemblies>

      </compilation>
      <pages>
          <namespaces>
            <clear />
            <add namespace="System" />
            <add namespace="System.Collections" />
            <add namespace="System.Collections.Specialized" />
            <add namespace="System.Configuration" />
            <add namespace="System.Runtime.Serialization" />
            <add namespace="System.ServiceModel" />
            <add namespace="System.Text" />
            <add namespace="System.Text.RegularExpressions" />
            <add namespace="System.Linq" />
            <add namespace="System.Web" />
            <add namespace="System.Web.Caching" />
            <add namespace="System.Web.SessionState" />
            <add namespace="System.Web.Security" />
            <add namespace="System.Web.Profile" />
            <add namespace="System.Web.UI" />
            <add namespace="System.Web.UI.WebControls" />
            <add namespace="System.Web.UI.WebControls.WebParts" />
            <add namespace="System.Web.UI.HtmlControls" />
          </namespaces>

          <controls>
            <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          </controls>

      </pages>
      <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
      -->
      <authentication mode="Windows" />
      <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

      <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
      </customErrors>
      -->


      <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      </httpHandlers>
      <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </httpModules>


    </system.web>

    <system.codedom>
      <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
                  type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
          <providerOption name="CompilerVersion" value="v3.5"/>
          <providerOption name="WarnAsError" value="false"/>
      </compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4"
                  type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
          <providerOption name="CompilerVersion" value="v3.5"/>
          <providerOption name="OptionInfer" value="true"/>
          <providerOption name="WarnAsError" value="false"/>
      </compiler>
      </compilers>
    </system.codedom>

    <system.web.extensions>
      <scripting>
      <webServices>
          <!--
            Uncomment this section to enable the authentication service. Include
            requireSSL="true" if appropriate.

          <authenticationService enabled="true" requireSSL = "true|false"/>
          -->
          <!--
            Uncomment these lines to enable the profile service, and to choose the
            profile properties that can be retrieved and modified in ASP.NET AJAX
            applications.

         <profileService enabled="true"
                           readAccessProperties="propertyname1,propertyname2"
                           writeAccessProperties="propertyname1,propertyname2" />
          -->
          <!--
            Uncomment this section to enable the role service.

          <roleService enabled="true"/>
          -->
      </webServices>
      <!--
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      -->
      </scripting>
    </system.web.extensions>
    <!--
      The system.webServer section is required for running ASP.NET AJAX under Internet
      Information Services 7.0.It is not necessary for previous version of IIS.
    -->
    <system.webServer>
      <validation validateIntegratedModeConfiguration="false"/>
      <modules>
      <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </modules>
      <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
             type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
             type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </handlers>
    </system.webServer>


</configuration>
      這個配置文件是2008自動生成的,我沒有做更改,其實,你只需要更改的是<system.serviceModel>這個Selection。當然,在<appSettings>塊中需改動你的數據庫連接字串,這個其實,也不需要我提醒嘍。然后新建一個Svc文件,該文件指明使用的語言和Service的名稱即可,只要一行即可:<%@ ServiceHostLanguage="VB"Debug="true"Service="HL.DALSQLServer.Osp.SQLDaoEmployee"%>7、至此,你已經在IIS服務端配置文件憶寫好,剩下就是去的IIS中配置了,這一步,跟平常配置Web程序一樣,沒多大分別。
8、好了,開始寫客戶端程序吧,這個其實很簡單,我也不說什么註意事項了,直接看代碼吧:

FrmEmployee
Imports HL.EntityReflect.Osp
Imports HL.Business.Osp

Public Class FrmEmployeeClass FrmEmployee

    Private strBS_NO As String = Nothing
    Private strBS_NAME As String = Nothing

    Private Sub btnQuery_Click()Sub btnQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuery.Click
      Try
            Dim proxy As BLEmployee = New BLEmployee("EmployeeEndpoint")
            Dim dataER As EREmployee() = proxy.Query()
            Me.dgvEmployee.DataSource = dataER
      Catch ex As Exception
            MessageBox.Show(ex.ToString())
      End Try
    End Sub

    Private Sub btnDelete_Click()Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
      Try
            Dim proxy As New BLEmployee("EmployeeEndpoint")
            Dim model As New EREmployee()
            model.strBS_NO = tbxBS_NO.Text.Trim()
            model.strBS_NAME = tbxBS_NAME.Text.Trim()
            proxy.Del(model)
            MessageBox.Show("Delete OK, please query again to see result!")
      Catch ex As Exception
            MessageBox.Show(ex.ToString())
      End Try
    End Sub

    Private Sub btnAdd_Click()Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
      Try
            Dim proxy As New BLEmployee("EmployeeEndpoint")
            Dim model As New EREmployee()
            model.strBS_NO = tbxBS_NO.Text.Trim()
            model.strBS_NAME = tbxBS_NAME.Text.Trim()
            proxy.Add(model)
            MessageBox.Show("Add OK, please query again to see result!")
      Catch ex As Exception
            MessageBox.Show(ex.ToString())
      End Try
    End Sub

    Private Sub btnModify_Click()Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
      Try
            Dim proxy As New BLEmployee("EmployeeEndpoint")
            Dim model As New EREmployee()
            model.strBS_NO = strBS_NO
            model.strBS_NAME = strBS_NAME
            proxy.Modify(model, tbxBS_NO.Text.Trim(), tbxBS_NAME.Text.Trim())
            MessageBox.Show("Modify OK, please query again to see result!")
      Catch ex As Exception
            MessageBox.Show(ex.ToString())
      End Try
    End Sub

    Private Sub btnCalculate_Click()Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
      Try
            Dim proxy As BLEmployee = New BLEmployee("EmployeeEndpoint")
            Me.tbxBS_NO.Text = String.Format("{0} + {1} ={2}", 1, 2, proxy.fAdd(1, 2))
      Catch ex As Exception
            MessageBox.Show(ex.ToString())
      End Try
    End Sub

    Private Sub dgvEmployee_SelectionChanged()Sub dgvEmployee_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvEmployee.SelectionChanged
      Try
            strBS_NO = dgvEmployee.Item(0, dgvEmployee.CurrentRow.Index).Value
            strBS_NAME = dgvEmployee.Item(1, dgvEmployee.CurrentRow.Index).Value
            tbxBS_NO.Text = strBS_NO
            tbxBS_NAME.Text = strBS_NAME
      Catch ex As Exception
            MessageBox.Show(ex.ToString())
      End Try
    End Sub
End Class
配置文件也只需注意<system.serviceModel>塊即可.如下所示:

WCFWin
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel >
    <client>
      <endpoint name="EmployeeEndpoint" address="http://localhost/HL.Service/SvcEmployee.svc" binding="basicHttpBinding" contract="HL.Shared.Osp.IEmployee"/>
    </client>
</system.serviceModel>
<system.diagnostics>
    <sources>
      <!-- This section defines the logging configuration for My.Application.Log -->
      <source name="DefaultSource" switchName="DefaultSwitch">
      <listeners>
          <add name="FileLog"/>
          <!-- Uncomment the below section to write to the Application Event Log -->
          <!--<add name="EventLog"/>-->
      </listeners>
      </source>
    </sources>
    <switches>
      <add name="DefaultSwitch" value="Information" />
    </switches>
    <sharedListeners>
      <add name="FileLog"
         type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
         initializeData="FileLogWriter"/>
      <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
      <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
    </sharedListeners>
</system.diagnostics>
</configuration>


9、說明一下,這個演示中的Demo使用的數據庫文件其實跟我去年寫的一篇WinForm下多层架构的实现使用的是同一個,當然,你也可以在下載專案的HL.Win找到,名稱為: Employee.txt,另外,本人的文筆不怎樣,沒法寫出很漂亮的文章出來,這也是為什么好久沒有寫博客的原因,尤其是這種帶有技朮性的文章。所以,說的不對或不好的地方,望諒解,當然,如果這篇文章能給你學習WCF帶來一點啟發或幫助,那麼也就不枉了我寫這篇文章的初衷了。

程序源文件下載

Kingna(jinliangliu#163.com)
2008/4/9於博客園
歡迎轉載,轉載請保留以上信息
页: [1]
查看完整版本: 基於IIS的WCF的分布式多層架構開發實現