Example of a calculator for WCF

Source: Internet
Author: User

for WCF, we have a theoretical foundation in front of Today, through an example of a calculator, we will explain how to create a complete WCF application step-by-step.


One, create the entire solution

    
        Calculator.service: A class library project, Define service contract, apply System.ServiceModel assemblies, and provide implementations of WCF services.

        Calculator.host: A Windows Forms application that implements a homestay for a service that is defined in a Calculator.service project that requires references to Calculator.service projects and System.ServiceModel assemblies.

        Calculator.client: A client of a Windows Forms application impersonation service that applies the System.ServiceModel assembly.

                                &N Bsp                          


ii. Create service contract

        In general, we define a service contract as a form of interface. The following code defines an interface ICalculator as a service contract. We define an interface as a service contract by applying the System.ServiceModel.ServiceContractAttribute attribute on the interface.

After the interface is defined as a service contract, the method members of the interface do not automatically become the operations of the service. We need to explicitly apply the OperationContractAttribute feature above the corresponding operation method.

Using system;using system.collections.generic;using system.linq;using system.text;using System.ServiceModel; namespace calculator.service{    [ServiceContract] public    interface ICalculator    {        [operationcontract ]        double Add (double x, double y);        [OperationContract]        Double Subtract (double x, double y);        [OperationContract]        Double Multiply (double x, double y);        [OperationContract]        Double Divide (double x, double y);}    }


Iii. creation of services

When the service contract is created successfully, we need to create the specific WCF service by implementing the service contract, and the WCF service CalculatorService implements the interface ICalculator of the service contract and realizes all service operation.

Using system;using system.collections.generic;using system.linq;using system.text;namespace Calculator.Service{ Public    class Calculatorservice:icalculator    {public        double Add (double x, double y)        {            return x + y;        }        Public double Subtract (double x, double y)        {            return x-y;        }        Public double Multiply (double x, double y)        {            return x * y;        }        Public double Divide (double x, double y)        {            return x/y;}}    }


Iv. Homestay services through self-boarding

The purpose of a service host is to open a process that provides a running environment for WCF services. Expose to potential service consumers by adding one or more intermediate orders to the service. The service consumer eventually invokes the service through a matching endpoint. We can complete all the service boarding work in a code way.

Using calculator.service;using system;using system.collections.generic;using system.componentmodel;using System.data;using system.drawing;using system.linq;using system.servicemodel;using System.ServiceModel.Description        ; using system.text;using system.windows.forms;namespace calculator.host{public partial class Form1:form {        Public Form1 () {InitializeComponent ();        } ServiceHost host = null; private void Btnopen_click (object sender, EventArgs e) {host = new ServiceHost (typeof (CalculatorService                        )); Host.            AddServiceEndpoint (typeof (ICalculator), New Wshttpbinding (), "Http://localhost:8008/Calculator"); if (host. Description.behaviors.find<servicemetadatabehavior> () ==null) {ServiceMetadataBehavior Beh                Avior = new ServiceMetadataBehavior (); Behavior.                Httpgetenabled = true; Behavior. Httpgeturl = new Uri ("Http://localhost:8008/CalcuLator/metadata "); Host.            DESCRIPTION.BEHAVIORS.ADD (behavior); } host. Opened + = delegate {Label1. Text = "The service has started!"            "; }; Host.                    Open (); The private void btnClose_Click (object sender, EventArgs e) {if (host. state! = communicationstate.closed) {host. Closed + = delegate {Label1. Text = "Service has stopped!"                "; }; Host.            Close (); }        }    }}



V. Create a client Invoke service

After the service has been successfully hosted, the server starts listening for the service invocation request. In addition, service homestay will publish the service description in the form of metadata, the corresponding client can obtain the metadata, create love your client program to service the consumption. At VS, when we add a service reference, vs internally helps us to get the metadata, and borrows the set of these metadata through the code generation tool to automatically generate the service proxy-related code and the corresponding configuration for the service invocation.




We can create the Calculatorclient object and execute the corresponding method invoke service operation.

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing;  Using system.linq;using system.text;using system.windows.forms;namespace calculator.client{public partial class Form1        : Form {public Form1 () {InitializeComponent ();        } private void Form1_Load (object sender, EventArgs e) {combobox1.text = "+"; } private void Button1_Click (object sender, EventArgs e) {calculatorservice.calculatorclient CLI            ent = new Calculatorservice.calculatorclient ();            Double x = convert.todouble (TextBox1.Text);            Double y = convert.todouble (TextBox2.Text);            Double result=0;            string operater = Combobox1.text; Switch (operater) {case ' + ': result = client.                    ADD (x, y);                Break Case "-": result = client.  Subtract (x, y);                  Break Case "*": result = client.                    Multiply (x, y);                Break Case "/": if (y==0) {MessageBox.Show ("divisor cannot be 0!                        ");                    Return } result = client.                    Divide (x, y);            Break } Label1.                              Text = TextBox1.Text + combobox1.text + textbox2.text + "=" + convert.tostring (Result); }    }}





In this calculator example, we implement a simple Computing service (CalculatorService) that provides basic operations for addition, subtraction, multiplication, and addition. Clients and services are simulated by running in different processes, reflecting the relationship that the client and the server process call each other.









Example of a calculator for WCF

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.