A journey to WCF-the first WCF example (III) and the wcf example

Source: Internet
Author: User

A journey to WCF-the first WCF example (III) and the wcf example
Step 5: Create a client

After the WCF application service is successfully hosted, the WCF Service application starts listening for service call requests. In addition, the service host publishes the service description in the form of metadata, and the corresponding client can obtain the metadata. Next, we will create a client program to call the service.

1) run the service boarding program (hosting.exe ).

2) In "solution Resource Manager" in Visual Studio 2015, expand the WinClient project, left-click to select "Reference", and right-click the project to bring up the menu, in the context menu, select "Add Service References )". For example.

3) a dialog box is displayed, as shown in. In the "Address" input box of the dialog box, enter the source address of the Service metadata release: http: // 127.0.0.1: 8888/BookService/metadata, and enter a namespace in the "namespace" input box, click "OK", for example ). Visual studio 2015 automatically generates a series of code and configuration for service calling.

 

 Add service reference

4) A Class automatically generated in Visual Studio 2015 contains a service agreement interface, a service proxy object, and other related classes. Directly used by the client for service calling is a service proxy BookServiceClient that inherits from ClientBase <IBookService> and implements the IBookService interface. For example.

 

5) the specific implementation of BookServiceClient is as follows.

 

 

6) We can instantiate the BookServiceClient object and execute the corresponding method to call the WCF Service operation. The code used by the client to call the WCF Service is as follows:

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WinClient{    public partial class FrmBook : Form    {        public FrmBook()        {            InitializeComponent();        }        private void btnGetBook_Click(object sender, EventArgs e)        {            BookServiceRef.Books book = new BookServiceRef.Books();            BookServiceRef.BookServiceClient bookSvrClient = new BookServiceRef.BookServiceClient();            textBoxMsg.Text= bookSvrClient.GetBook("3");            book = XMLHelper.DeSerializer<BookServiceRef.Books>(textBoxMsg.Text);            txtBookId.Text = book.BookID.ToString();            txtAuthorID.Text = book.AuthorID.ToString();            textBoxName.Text = book.Name;            textBoxCategory.Text = book.Category.ToString();            textBoxPrice.Text = book.Price.ToString();        }    }}

 

The result after running, such.

 

Step 6: the client uses ChannelFactory <T> to call the WCF Service

The client calls a service through a service proxy object. The preceding example creates an automatically generated type object inherited from ClientBase <T> to call a service. In fact, we also have another method to create a service proxy, that is, using ChannelFactory <T>. In addition, WCF uses a protocol-based service call method. As shown in the preceding example, Visual Studio 2015 adds a service reference, A service agreement interface equivalent to the server is created on the client. In our example, because both the server and client are in the same solution, the server and client can reference the same protocol.

1) to implement the function of calling the WCF Service through ChannelFactory <T>, we need to add a new project named SCF. contracts, put the original in SCF. IBookService in the WcfService project. move the cs file to SCF. change the namespace in the Contracts project. The SCF. WcfService and WinClient projects add references to the SCF. Contracts project at the same time. The final project structure is shown in.

 

2) We will use ChannelFactory <IBookService> to create a service proxy object through the IBookService agreement interface in this SCF. Contracts project to directly call the corresponding service. We first implement all the methods for creating service proxies and calling services based on channelfacoprocessor <T> in the code. The Code is as follows:

private void buttonChannelFactory_Click(object sender, EventArgs e)        {            using (ChannelFactory<IBookService> channelFactory = new ChannelFactory<IBookService>                (new WSHttpBinding(), "http://127.0.0.1:8888/BookService"))            {                IBookService proxy = channelFactory.CreateChannel();                using (proxy as IDisposable)                {                    textBoxMsg.Text = proxy.GetBook("4");                    Books book = XMLHelper.DeSerializer<Books>(textBoxMsg.Text);                    txtBookId.Text = book.BookID.ToString();                    txtAuthorID.Text = book.AuthorID.ToString();                    textBoxName.Text = book.Name;                    textBoxCategory.Text = book.Category.ToString();                    textBoxPrice.Text = book.Price.ToString();                }            }            }

 

3) Click "ChannelFactory method". The result is shown in.

 

4) because the endpoint is the only means for communication by WCF, ChannelFactory <T> essentially creates a Service proxy for service calling through the specified endpoint. In the code above, when creating the ChannelFactory <T>, specify the relevant elements of the endpoint in the constructor (the Protocol is represented by the paradigm type, address and binding are specified through parameters ). The above method directly writes the corresponding address and binding in the code, which is inconvenient for later maintenance. In actual WCF applications, the address and binding are generally written in the configuration file, and then the service is called by reading the configuration file. In the app. config configuration file, we configure the three elements of the specified endpoint, and specify an endpoint configuration name (BookService) for the corresponding endpoint ). The configuration information is as follows:

<?xml version="1.0" encoding="utf-8" ?><configuration>    <startup>        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />    </startup>    <system.serviceModel>        <bindings>            <wsHttpBinding>                <binding name="WSHttpBinding_IBookService" />            </wsHttpBinding>        </bindings>        <client>            <endpoint address="http://127.0.0.1:8888/BookService" binding="wsHttpBinding"                bindingConfiguration="WSHttpBinding_IBookService" contract="SCF.Contracts.IBookService"                name="WSHttpBinding_IBookService">                <identity>                    <userPrincipalName value="DEVELOPER\Administrator" />                </identity>            </endpoint>        </client>    </system.serviceModel></configuration>

 

 

5) Next we will create a ChannelFactory <T> object through the configuration information. At this time, we do not need to specify the binding and address of the endpoint, but only need to specify the corresponding endpoint configuration name. The Code is as follows.

 

  private void buttonChannelConfig_Click(object sender, EventArgs e)        {            using (ChannelFactory<IBookService> channelFactory = new ChannelFactory<IBookService>("WSHttpBinding_IBookService"))            {                IBookService proxy = channelFactory.CreateChannel();                using (proxy as IDisposable)                {                    textBoxMsg.Text = proxy.GetBook("5");                    Books book = XMLHelper.DeSerializer<Books>(textBoxMsg.Text);                    txtBookId.Text = book.BookID.ToString();                    txtAuthorID.Text = book.AuthorID.ToString();                    textBoxName.Text = book.Name;                    textBoxCategory.Text = book.Category.ToString();                    textBoxPrice.Text = book.Price.ToString();                }            }        }

 

6) Click "ChannelFactorys configuration mode". The result is shown in.

 

 

 

Note: I encountered the following problems during the compilation of this sample project:

WCF The target computer actively rejects , Unable to connect Error

Error Description: The New WCF class library project is hosted by the WinForm program. There is no error during hosting, but the service cannot be found when the client references the service, if multiple services are enabled, the port usage error is not reported.

Solution:

1) Check the configuration file to see if the configuration information is correctly written.

2) restart your computer.

3) changed the configuration method to the direct code method.

4) when the WCF Service is not hosted, the service is referenced and the same error is prompted. I opened the listening port and looked for it carefully. I didn't find the port I defined as port 8888. It seems that the boarding of the WCF Service fails. If the boarding succeeds, the port must be in the listening status.

Solution: Remove using first, and try again. The reference service is successful, and the call is successful. It turns out that when using is used, if using is released, the host will be disabled by using, so the host will be immediately closed after the service is opened. Observe the differences between the following two sections of code.

Error code:

 

Static void Main (string [] args) {try {using (ServiceHost host = new ServiceHost (typeof (BookService) {host. opened + = delegate {Console. writeLine ("BookService, use the configuration file, press any key to terminate the service! ") ;}; Host. Open () ;}} catch (Exception ex) {Console. WriteLine (ex. Message) ;}console. Read ();}

 

Correct code:

Static void Main (string [] args) {try {using (ServiceHost host = new ServiceHost (typeof (BookService ))){
Host. Opened + = delegate {Console. WriteLine ("BookService, use the configuration file and press any key to terminate the service! ") ;}; Host. Open (); Console. Read () ;}} catch (Exception ex) {Console. WriteLine (ex. Message );}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.