Compartilhar via


Getting Started Sample

The Getting Started sample demonstrates how to implement a typical service and a typical client using Windows Communication Foundation (WCF). This sample is the basis for all other basic technology samples.

Note

The setup procedure and build instructions for this sample are located at the end of this topic.

ms751519.Important(en-us,VS.100).gif Note:
The samples may already be installed on your computer. Check for the following (default) directory before continuing.

<InstallDrive>:\WF_WCF_Samples

If this directory does not exist, go to Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4 to download all Windows Communication Foundation (WCF) and WF samples. This sample is located in the following directory.

<InstallDrive>:\WF_WCF_Samples\WCF\GettingStarted\GettingStarted

The service describes the operations it performs in a service contract that it exposes publicly as metadata. The service also contains the code to implement the operations.

The client contains a definition of the service contract and a proxy class for accessing the service. The proxy code is generated from the service metadata using the ServiceModel Metadata Utility Tool (Svcutil.exe).

On Windows Vista, the service is hosted in the Windows Activation Service (WAS). On Windows XP and Windows Server 2003, it is hosted by Internet Information Services (IIS) and ASP.NET. Hosting a service in IIS or WAS allows the service to be activated automatically when it is accessed for the first time.

Note

If you would prefer to get started with a sample that hosts the service in a console application instead of IIS, see the Self-Host sample.

The service and client specify access details in configuration file settings, which provide flexibility at the time of deployment. This includes an endpoint definition that specifies an address, binding, and contract. The binding specifies transport and security details for how the service is to be accessed.

The service configures a run-time behavior to publish its metadata.

The service implements a contract that defines a request-reply communication pattern. The contract is defined by the ICalculator interface, which exposes math operations (add, subtract, multiply, and divide). The client makes requests to a given math operation and the service replies with the result. The service implements an ICalculator contract that is defined in the following code.

' Define a service contract.
    <ServiceContract(Namespace:="http://Microsoft.Samples.GettingStarted")>
     Public Interface ICalculator
        <OperationContract()>
        Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()>
        Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()>
        Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()>
        Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
    End Interface
// Define a service contract.
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
    [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);
}

The service implementation calculates and returns the appropriate result, as shown in the following example code.

' Service class which implements the service contract.
Public Class CalculatorService
Implements ICalculator
Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
Return n1 + n2
End Function

Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Subtract
Return n1 - n2
End Function

Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Multiply
Return n1 * n2
End Function

Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Divide
Return n1 / n2
End Function
End Class
// Service class that implements the service contract.
public class CalculatorService : ICalculator
{
    public double Add(double n1, double n2)
    {
        return n1 + n2;
    }
    public double Subtract(double n1, double n2)
    {
        return n1 - n2;
    }
    public double Multiply(double n1, double n2)
    {
        return n1 * n2;
    }
    public double Divide(double n1, double n2)
    {
        return n1 / n2;
    }
}

The service exposes an endpoint for communicating with the service, defined using a configuration file (Web.config), as shown in the following sample configuration.

<services>
    <service 
        name="Microsoft.ServiceModel.Samples.CalculatorService"
        behaviorConfiguration="CalculatorServiceBehavior">
        <!-- ICalculator is exposed at the base address provided by
         host: https://localhost/servicemodelsamples/service.svc.  -->
       <endpoint address=""
              binding="wsHttpBinding"
              contract="Microsoft.ServiceModel.Samples.ICalculator" />
       ...
    </service>
</services>

The service exposes the endpoint at the base address provided by the IIS or WAS host. The binding is configured with a standard WSHttpBinding, which provides HTTP communication and standard Web service protocols for addressing and security. The contract is the ICalculator implemented by the service.

As configured, the service can be accessed at https://localhost/servicemodelsamples/service.svc by a client on the same computer. For clients on remote computersto access the service, a fully-qualified domain name must be specified instead of localhost.

The framework does not expose metadata by default. As such, the service turns on the ServiceMetadataBehavior and exposes a metadata exchange (MEX) endpoint at https://localhost/servicemodelsamples/service.svc/mex. The following configuration demonstrates this.

  <system.serviceModel>
    <services>
      <service 
          name="Microsoft.ServiceModel.Samples.CalculatorService"
          behaviorConfiguration="CalculatorServiceBehavior">
        ...
        <!-- the mex endpoint is explosed at
         https://localhost/servicemodelsamples/service.svc/mex -->
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>

    <!--For debugging purposes set the includeExceptionDetailInFaults
     attribute to true-->
    <behaviors>
      <serviceBehaviors>
        <behavior name="CalculatorServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

The client communicates using a given contract type by using a client class that is generated by the ServiceModel Metadata Utility Tool (Svcutil.exe). This generated client is contained in the file generatedClient.cs or generatedClient.vb. This utility retrieves metadata for a given service and generates a client for use by the client application to communicate using a given contract type. The hosted service must be available to generate the client code, because the service is used to retrieve the updated metadata.

Run the following command from the SDK command prompt in the client directory to generate the typed proxy:

svcutil.exe /n:"http://Microsoft.ServiceModel.Samples,Microsoft.ServiceModel.Samples" https://localhost/servicemodelsamples/service.svc/mex /out:generatedClient.cs

To generate client in Visual Basic type the following from the SDK command prompt:

Svcutil.exe /n:"http://Microsoft.ServiceModel.Samples,Microsoft.ServiceModel.Samples" https://localhost/servicemodelsamples/service.svc/mex /l:vb /out:generatedClient.vb

By using the generated client, the client can access a given service endpoint by configuring the appropriate address and binding. Like the service, the client uses a configuration file (App.config) to specify the endpoint with which it wants to communicate. The client endpoint configuration consists of an absolute address for the service endpoint, the binding, and the contract, as shown in the following example.

<client>
     <endpoint
         address="https://localhost/servicemodelsamples/service.svc" 
         binding="wsHttpBinding" 
         contract=" Microsoft.ServiceModel.Samples.ICalculator" />
</client>

The client implementation instantiates the client and uses the typed interface to begin communicating with the service, as shown in the following example code.

' Create a client
Dim client As New CalculatorClient()

' Call the Add service operation.
            Dim value1 = 100.0R
            Dim value2 = 15.99R
            Dim result = client.Add(value1, value2)
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result)

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

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

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

'Closing the client gracefully closes the connection and cleans up resources
// Create a client.
CalculatorClient client = new CalculatorClient();

// 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);

//Closing the client releases all communication resources.
client.Close();

When you run the sample, the operation requests and responses are displayed in the client console window. Press ENTER in the client window to shut down the client.

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 Getting Started sample shows the standard way to create a service and client. The other Basic Windows Communication Foundation Technology Samples build on this sample to demonstrate specific product features.

To set up, build, and run the sample

  1. Ensure that you have performed the One-Time Setup Procedure for the Windows Communication Foundation Samples.

  2. To build the C# or Visual Basic .NET edition of the solution, follow the instructions in Building the Windows Communication Foundation Samples.

  3. To run the sample in a single- or cross-computer configuration, follow the instructions in Running the Windows Communication Foundation Samples.

See Also

Tasks

How to: Host a WCF Service in a Managed Application
How to: Host a WCF Service in IIS