WCF learning journey-Example 4 (30) and Example 3

Source: Internet
Author: User
Tags connectionstrings

WCF learning journey-Example 4 (30) and Example 3
Going on to the WCF learning journey-one of the third examples)WCF learning journey-Example 2 (28th)

WCF learning journey-Example 3 (19th)

In the previous article, we created a WCF server application. In this article, we will learn how to create a WCF Server Host Program and a client call program.

For more information about how to host a website, refer to the following article: WCF Study Tour-preparations before WCF boarding (8), WCF Study Tour-deploying the WCF Service to IIS7.5 (9 ), WCF learning journey-deploying a WCF Service to an application (10), a WCF learning journey-boarding a Windows Service Program for the WCF Service (11 ), WCF learning tour-WAS boarding of the WCF Service (12), WCF learning tour-Batch boarding of the WCF Service (13)

For detailed steps, see the following.

7. Create a Host Program for the WCF Server
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. The App. config configuration file in BookMgr. Hosting is as follows:

<?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. The code for Program. cs in BookMgr. Hosting is as follows:

 

Using BookMgr. service; 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 ("BookServi Ce, use the configuration file and press any key to terminate the service! ") ;}; Host. open (); Console. foregroundColor = ConsoleColor. yellow; foreach (ServiceEndpoint se in host. description. endpoints) {Console. writeLine ("[endpoint]: {0} \ r \ n \ t [A-address]: {1} \ r \ n \ t [B-binding]: {2} \ r \ n \ t [C-Protocol]: {3} ", se. name, se. address, se. binding. name, se. contract. name);} Console. read () ;}} catch (Exception ex) {Console. writeLine (ex. message );}}}}

In the next step, you will create a Windows Forms client application to use the service.

8. Create a Windows client application
 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. On the menu bar, select "debug" and "Start debug" to run the application.

5. In the text box in the red box, enter IBM and click "query. Only books of the IBM type will be displayed. For example.

Now that you have an application that you can use, the application displays a list of books in the BookService. If you want to publish other data through this service, you can modify the object data model to include other tables in the database.

 

Note: If the following exception occurs during the encoding process:

Error message:

The communication object System. ServiceModel. Channels. ServiceChannel cannot be used for communication because it is in the "error" status.

Check the error message above to determine what is going on, debug it, and view the error information exposed in WCF, as shown below:

The System. data. sqlClient "ADO. NET provider load the Entity Framework provider type registered in the application configuration file "System. data. entity. sqlServer. sqlProviderServices, EntityFramework. sqlServer ". Make sure that the name of the restricted assembly is used and the Assembly is available to running applications. For more information, see http://go.microsoft.com/fwlink? LinkId = 260882.

 

The cause of the error is that the reference to EntityFramework. SqlServer. dll is missing in the BookMgr. Hosting project.

Solution: add the EntityFramework package to the BookMgr. Hosting project through nuget, such. The original reference figure is shown in Figure 2. After adding the reference, such as 3.

Figure 1

Figure 2

Figure 3

 

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.