Getting started with WCF-Pure code implementation start and reference WCF

Source: Internet
Author: User
Tags readline port number



These days, while Idle began to learn WCF, the Internet to find a lot of information to see, the results are to this data corresponding to that information, feel very inconvenient, now write down some of their own summary, hope to help to want to get started WCF friends.

Main references: Address: http://msdn.microsoft.com/en-us/library/ms734712.aspx


Create a WCF with the following six-step main sub-walk:


(MSDN description steps:)


How to: Define a Windows communication Foundation service contract
Describes how to create a WCF contract using a user-defined interface. The contract is used to define the functionality that the service provides to the outside world and to describe how the service communicates with the potential users of the outside world.


How to: Implement the Windows communication Foundation service contract
Describes how to implement a service contract. Once a contract has been created, the functionality provided by the service must be implemented in a class that inherits from the interface that defines the contract.


How to: Host and run a basic Windows communication Foundation Service
Describes how to configure endpoints for services in code, and how to host services and start services within a console application. To activate a service, you must configure and host the service in the run-time environment. This environment creates a service and controls its context and lifetime.


How to: Create a Windows communication Foundation client
Describes how to retrieve the metadata that is used to create a WCF client from a WCF service. This procedure uses the ServiceModel metadata utility (Svcutil.exe) provided by WCF.


How to: Configure a basic Windows communication Foundation Client
Describes how to configure a base client that is created by using the ServiceModel metadata utility (Svcutil.exe). The configuration client needs to specify the endpoint that the client uses to access the service.


How to: Use the Windows communication Foundation Client
Describes how to use the WCF client proxy generated by the ServiceModel metadata utility (Svcutil.exe) to invoke the functionality provided by the service.
The specific implementation steps are as follows:


Create a solution first.
Build a console Application project called Server under this solution, and then build a console application project called client.
Add a reference to System.ServiceModel for each item separately


When you create a basic WCF service, the first task is to define the contract. The contract specifies the operations supported by the service. You can treat an operation as a Web service method. You can create a contract by defining a C + +, C #, or VB interface. Each method in the interface corresponds to a specific service operation. Each interface must apply ServiceContractAttribute to itself, and each operation must apply OperationContractAttribute to itself. If a method in an interface has ServiceContractAttribute and no OperationContractAttribute, the method is not exposed.


After the server is created, change the default service namespace to Microsoft.ServiceModel.Samples.


Edit the program of the server (note the using System.ServiceModel and using System.ServiceModel.Description)


The server-side program code is as follows:

Using System;
Using System.ServiceModel;

Using System.ServiceModel.Description; namespace Microsoft.ServiceModel.Samples {//define an interface contract (MSDN First step: Define a service contract)//define a new interface named ICalculator, and apply a namespace value to the interface The ServiceContractAttribute property of the "Http://Microsoft.ServiceModel.Samples".
    Explicitly specifying a namespace is a best practice because it prevents the default namespace value from being added to the contract name. [ServiceContract (Namespace = "http://Microsoft.ServiceModel.Samples")] public interface ICalculator {//below
        Is the four method that defines subtraction [OperationContract] double Add (double n1, double n2);
        [OperationContract] Double Subtract (double n1, double n2);
        [OperationContract] Double Multiply (double n1, double n2);  

    [OperationContract] Double Divide (double n1, double n2); }//Implement Interface (MSDN Second step: Implement service contract) public class Calculatorservice:icalculator {public double Add (double N1,
            Double n2) {Double result = n1 + N2;
     Console.WriteLine ("Received Add ({0},{1})", N1, N2);       Console.WriteLine ("Return: {0}", result);
        return result;
            } public double Subtract (double n1, double n2) {double result = n1-n2;
            Console.WriteLine ("Received Subtract ({0},{1})", N1, N2);
            Console.WriteLine ("Return: {0}", result);
        return result;
            } public double Multiply (double n1, double n2) {Double result = N1 * N2;
            Console.WriteLine ("Received Multiply ({0},{1})", N1, N2);
            Console.WriteLine ("Return: {0}", result);
        return result;
            } public double Divide (double n1, double n2) {double result = n1/n2;
            Console.WriteLine ("Received Divide ({0},{1})", N1, N2);
            Console.WriteLine ("Return: {0}", result);
        return result;
            }} class Program {static void Main (string[] args) {//Host and Run service (MSDN Step III) Configure a base for a serviceAddress//1. Creates a Uri instance for the base address of the service.
            This URI specifies the HTTP scheme, the local computer, the port number 8000, and the service path specified in the service contract for the service namespace, Servicemodelsample/service.

            Uri baseaddress = new Uri ("Http://localhost:8000/ServiceModelSamples/Service"); The hosting service//1. Import the System.ServiceModel.Description namespace.
            This line of code should be placed at the top of the Program.cs/program.vb file along with the rest of the using or imports statements. 2. Create a new ServiceHost instance to host the service. You must specify the type that implements the service contract and base address.
            For this example, the base address is http://localhost:8000/ServiceModelSamples/Service,CalculatorService for the type that implements the service contract.
            ServiceHost selfhost = new ServiceHost (typeof (CalculatorService), baseaddress); 3. Add a Try-catch statement that captures Communicationexception and add the code to the try block in the next three steps.
            The catch clause should display an error message and then call Selfhost.abort (). try {//4. Add a public service endpoint. To do this, you must specify the addresses of the protocols, bindings, and endpoints exposed by the endpoint. For this example, ICalculator is specified as a contract, Wshttpbinding is specified as a binding, and CalculatorService is specified as an address. Note here that the endpoint address is a relative address. The full address of the endpoint is a combination of base and endpoint addresses.
In this example, the full address is http://localhost:8000/ServiceModelSamples/Service/CalculatorService.                Selfhost.addserviceendpoint (typeof (ICalculator), New Wshttpbinding (
                ), "CalculatorService"); 5. Enable metadata Exchange. To do this, add the service metadata behavior.
                First create a ServiceMetadataBehavior instance, set the Httpgetenabled property to True, and then add a new behavior for the service.
                ServiceMetadataBehavior SMB = new ServiceMetadataBehavior (); Smb.
                Httpgetenabled = true;
                SELFHOST.DESCRIPTION.BEHAVIORS.ADD (SMB); 6. Open ServiceHost and wait for incoming messages.
                When the user presses the ENTER key, close ServiceHost Selfhost.open ();
                Console.WriteLine ("The service is ready.");
                Console.WriteLine ("Press <ENTER> to terminate service.");
                Console.WriteLine ();
                
                Console.ReadLine ();
            Selfhost.close (); } catch (Communicationexception CE) {Console.WriteLine ("An exception occurred: {0} ", CE.
                Message); SelfhosT.abort (); }
        }
    }
}


At this, the server is well-equipped.


Verify that the service is running correctly


1. Run Service.exe from within Visual Studio. When running on Windows Vista, you must run the service with administrator privileges. Because Visual Studio runs with administrator privileges, Service.exe is also run with administrator privileges. You can also start a new command prompt, run it with administrator privileges, and run service.exe in it.


2. Open Internet Explorer and browse to the debug page for the service (URL http://localhost:8000/ServiceModelSamples/Service).


Configure the client created: (Creating the client is the fourth step in MSDN)


Step: (Below is the fifth step in MSDN, configure the client)


1. First run the well-written server, which can be run by F5 in the project


2. On the Start menu, click All Programs, and then click Visual Studio 2008. Click Visual Studio Tools, and then click Visual Studio 2008 Command prompt.


3. Navigate to the directory where you want to place the client code. For example:


4. Generate the file with the following command:

D:\wcf\wcfdemo\wcfsample\client>svcutil.exe/language:cs/out:generatedproxy.cs/config:app.config/HTTP Localhost:8000/servicemodelsamples/service
5. Add the generated app. Config and GeneratedProxy.cs files to the client's project


The end is the use of the client (sixth step in MSDN)


The program code for the client is as follows:
Using System;

Using System.ServiceModel; Namespace Client {class Program {static void Main (string[] args) {//step 1:create
            An endpoint address and an instance of the WCF Client.
            Create a EndpointAddress instance for the base address of the service to invoke, and then create the WCF Client object. EndpointAddress epaddress = new EndpointAddress ("http://localhost:8000/ServiceModelSamples/Service/
            CalculatorService ");


            Calculatorclient client = new Calculatorclient (new Wshttpbinding (), epaddress);  
            Step 2:call the service operations.
            Invokes a client operation from within client.
            Call the ADD service operation.
            Double value1 = 100.00D;
            Double value2 = 15.99D; Double result = client.
            ADD (value1, value2);

            Console.WriteLine ("Add ({0},{1}) = {2}", value1, value2, result);   
            Call the Subtract service operation.
            value1 = 145.00D;
            value2 = 76.54D; result = client. SubtraCT (value1, value2);

            Console.WriteLine ("Subtract ({0},{1}) = {2}", value1, value2, result);   
            Call the Multiply service operation.
            value1 = 9.00D;
            value2 = 81.25D; result = client.
            Multiply (value1, value2);

            Console.WriteLine ("Multiply ({0},{1}) = {2}", value1, value2, result);   
            Call the Divide service operation.
            value1 = 22.00D;
            value2 = 7.00D; result = client.
            Divide (value1, value2);

            Console.WriteLine ("Divide ({0},{1}) = {2}", value1, value2, result);   
            Step 3:closing The client gracefully closes the connection and cleans up resources.
            Call Close on the WCF client and wait until the user presses Enter to terminate the application. Client.

            Close ();
            Console.WriteLine ();
            Console.WriteLine ("Press <ENTER> to terminate client.");  

        Console.ReadLine (); }
    }
}

Here, the entire server and client are written.


Verify that the service is running correctly


1. First find the project inside the compiled server, for example: D:\WCF\WCFDEMO\WCFSample\Server\bin\Debug, start the inside of the Server.EXE


2. Start the client, which can be initiated in the solution, press F5, and if you see the following results, it proves successful.

ADD (100,15.99) = 115.99
Subtract (145,76.54) = 68.46
Multiply (9,81.25) = 731.25
Divide (22,7) = 3.14285714285714 Press
<ENTER> to terminate client.


The entire project structure, such as screenshots:


http://blog.163.com/glq_19/blog/static/127417581201052875239622/

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.