WCF學習之旅—第三個示例之四(三十)


       上接WCF學習之旅—第三個示例之一(二十七)

              WCF學習之旅—第三個示例之二(二十八)

             WCF學習之旅—第三個示例之三(二十九)

          在上一篇文章中我們創建了WCF服務端應用程序,在這一篇文章中我們來學習如何創建WCF的服務端寄宿程序與客戶端調用程序。

          關於如何寄宿可以參考以下文章WCF學習之旅—WCF寄宿前的准備(八), WCF學習之旅—WCF服務部署到IIS7.5(九),WCF學習之旅—WCF服務部署到應用程序(十)WCF學習之旅—WCF服務的Windows 服務程序寄宿(十一)WCF學習之旅—WCF服務的WAS寄宿(十二)WCF學習之旅—WCF服務的批量寄宿(十三)

          具體步驟見下面。

七、創建WCF服務端寄宿程序

  1. WCF服務需要依存一個運行着的進程(宿主),服務寄宿就是為服務指定一個宿主的過程。
  2. 我們在BookMgr.Hosting項目中通過配置方式完成所有的服務寄宿工作,下面的代碼是通過一個控制台應用對 BookService的寄宿的實現。關於配置方式參見前一文章。
  3. 如果在運行的過程中會出現以下錯誤信息:“在服務“BookService”實現的協定列表中找不到協定名稱“BookMgr.Contracts.IBookService”。則回到BookMgr.Contracts項目中修改接口文件代碼如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
 

namespace BookMgr.Contracts
{

    [ServiceContract]
    public interface IBookService
    {
        [OperationContract]
        string Add(string bookInfo);

        [OperationContract]
        string Edit(string bookInfo);

        [OperationContract]
        string Get(string bookId);

        [OperationContract]
        string Delete(string bookInfo);

        [OperationContract]
        string Search(string Category, string searchString); 

    }
}

 

      4. BookMgr.Hosting 中的App.config配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" /> </configSections> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <connectionStrings> <add name="BookEntities" connectionString="metadata=res://*/BookModel.csdl|res://*/BookModel.ssdl|res://*/BookModel.msl;
provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=Test;
integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
providerName="System.Data.EntityClient" /> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <system.serviceModel> <diagnostics> <messageLogging logEntireMessage="true" logKnownPii="false" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" /> <endToEndTracing propagateActivity="true" activityTracing="true" messageFlowTracing="true" /> </diagnostics> <behaviors> <serviceBehaviors> <behavior name="metadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8088/BookService/metadata" /> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="metadataBehavior" name="BookMgr.Service.BookService"> <endpoint address="http://127.0.0.1:8088/BookService" binding="wsHttpBinding" contract="BookMgr.Contracts.IBookService" /> </service> </services> </system.serviceModel> </configuration>

       5. BookMgr.Hosting中的Program.cs的代碼如下:

 

using BookMgr.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

 

namespace BookMgr.Hosting
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (ServiceHost host = new ServiceHost(typeof(BookService)))

                {
                    host.Opened += delegate
                    {
                        Console.WriteLine("BookService,使用配置文件,按任意鍵終止服務!");

                    };
                    host.Open();
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    foreach (ServiceEndpoint se in host.Description.Endpoints)
                    {
                        Console.WriteLine("[終結點]: {0}\r\n\t[A-地址]: {1} \r\n\t [B-綁定]: {2} \r\n\t [C-協定]: {3}",

                     se.Name, se.Address, se.Binding.Name, se.Contract.Name); 

                    }

                    Console.Read();
                }
            }
            catch (Exception ex)

            {
                Console.WriteLine(ex.Message);

            }
        }
    }
}
 

        在接下來的步驟中,將創建一個 Windows 窗體客戶端應用程序以使用該服務。

八、創建客戶端Windows應用程序

  1. 在菜單欄上,依次選擇“文件-->添加-->新建項目”。
  2. 在“添加新項目”對話框中,展開 “Visual C#”節點,選擇“Windows”節點,然后選擇“Windows 窗體應用程序”。
  3. 在“名稱”文本框中,輸入 BookMgr.Client,然后選擇“確定”按鈕。 如下圖。

        4. 在解決方案資源管理器中,添加一些引用,如下圖。       5. 在菜單欄上,選擇“項目”、“設為啟動項目”。

      6. 在“解決方案資源管理器”窗口中,選中“BookMgr.Client”項目,彈出右鍵菜單,選擇“添加—》新建項”。        7. 在“Windows Forms”節點下,選擇“Windows窗體”,新建一個FrmBook.cs文件。如下圖。       8. 在FrmBook窗體界面中按下圖,進行拖放窗體控件。

九、添加篩選功能

       在此步驟中,將在應用程序中添加根據書籍的類型篩選書籍數據的功能。

  1. 在解決方案資源管理器中,選中“FrmBook.cs”文件,在彈出的右鍵菜單中選擇“打開”,或者使用鼠標左鍵雙擊。
  2. 將工具箱中的 Lable 控件、TextBox控件和 Button 控件添加到窗體。
  3. 打開 Button 控件的快捷菜單,選擇“查看代碼”,然后在 btnSearchCategory_Click事件處理程序中添加以下代碼:
 private void btnSearchCategory_Click(object sender, EventArgs e)
        {
            try
            {
                using (ChannelFactory<IBookService> channelFactory = new ChannelFactory<IBookService>("WSHttpBinding_IBookService"))
                {
                    IBookService proxy = channelFactory.CreateChannel();

                    using (proxy as IDisposable)
                    {
                        textBoxMsg.Text = proxy.Search(txtCategory.Text, string.Empty);
                        List<Books> books = XMLHelper.DeSerializer<List<Books>>(textBoxMsg.Text);
                        gridBooks.DataSource = books;
                    }
                }

            }
            catch (Exception ex)
            {
                textBoxMsg.Text = ex.Message;

            }

        }

 

       4. 在菜單欄上,依次選擇“調試”和“啟動調試”以運行應用程序。

       5.  在紅框中的文本框中,輸入 IBM,然后使用鼠標點擊“查詢”按鈕。 將僅顯示來自 類型為IBM 的書籍。如下圖。

 

現在,你有了一個可以使用的應用程序,該應用程序將顯示 BookService服務中的書籍列表。 如果希望通過該服務公開其他數據,則可以修改實體數據模型以包括數據庫中的其他表。

 

注:如果在進行這一步驟中的編碼過程中,出現了以下異常錯誤信息:

錯誤信息:

通信對象 System.ServiceModel.Channels.ServiceChannel 無法用於通信,因為其處於“出錯”狀態。

光看上面的錯誤信息無法判斷到底是怎么回事,進行調試,查看WCF內部暴露的錯誤信息,如下

無法為具有固定名稱“System.Data.SqlClient”的 ADO.NET 提供程序加載在應用程序配置文件中注冊的實體框架提供程序類型“System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer”。請確保使用限定程序集的名稱且該程序集對運行的應用程序可用。有關詳細信息,請參閱 http://go.microsoft.com/fwlink/?LinkId=260882

 

這個異常,最后我找到出錯的原因是:由於BookMgr.Hosting項目缺少對EntityFramework.SqlServer.dll的引用。

解決方法:為BookMgr.Hosting項目通過nuget添加上EntityFramework包,如下圖一。原來的引用圖如下圖二,添加引用之后,如下圖三。

 

圖1

 

圖2

 

圖3

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM