Professional Documents
Culture Documents
How To WCF - HOST
How To WCF - HOST
This is the third of six tasks required to create a basic Windows Communication Foundation
(WCF) service and a client that can call the service. For an overview of all six of the tasks,
see the Getting Started Tutorial topic.
This topic describes how to run a basic Windows Communication Foundation (WCF) service.
This procedure consists of the following steps:
A complete listing of the code written in this task is provided in the example following the
procedure. Add the following code into the Main() method defined in the Program class.
This class was generated when you created the Service solution.
VB
C#
C++
F#
JScript
Copy
VB
C#
C++
F#
JScript
Copy
using System.ServiceModel.Description;
2. Create a new ServiceHost instance to host the service. You must specify the type that
implements the service contract and the base address. For this sample the base address
is http://localhost:8000/ServiceModelSamples/Service and
CalculatorService is the type that implements the service contract.
VB
C#
C++
F#
JScript
Copy
3. Add a try-catch statement that catches a CommunicationException and add the code
in the next three steps to the try block. The catch clause should display an error
message and then call selfHost.Abort().
VB
C#
C++
F#
JScript
Copy
try
{
// ...
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
4. Add an endpoint that exposes the service. To do this, you must specify the contract
that the endpoint is exposing, a binding, and the address for the endpoint. For this
sample, specify ICalculator as the contract, WSHttpBinding as the binding, and
CalculatorService as the address. Notice here the endpoint address is a relative
address. The full address for the endpoint is the combination of the base address and
the endpoint address. In this case the full address is
http://localhost:8000/ServiceModelSamples/Service/CalculatorService.
VB
C#
C++
F#
JScript
Copy
selfHost.AddServiceEndpoint(
typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
Note:
Starting with .NET Framework 4, if no endpoints are explicitly configured for the
service then the runtime adds default endpoints when the ServiceHost is opened. This
example explicitly adds an endpoint to provide an example of how to do so. For more
information about default endpoints, bindings, and behaviors, see Simplified
Configuration and Simplified Configuration for WCF Services.
5. Enable Metadata Exchange. To do this, add a service metadata behavior. First create a
ServiceMetadataBehavior instance, set the HttpGetEnabled property to true, and then
add the new behavior to the service. For more information about security issues when
publishing metadata, see Security Considerations with Metadata.
VB
C#
C++
F#
JScript
Copy
6. Open the ServiceHost and wait for incoming messages. When the user presses the
ENTER key, close the ServiceHost.
VB
C#
C++
F#
JScript
Copy
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
VB
C#
C++
F#
JScript
Copy
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Microsoft.ServiceModel.Samples
{
// 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);
}
try
{
}
}
}
Note:
Services such as this one require permission to register HTTP addresses on the machine for
listening. Administrator accounts have this permission, but non-administrator accounts must
be granted permission for HTTP namespaces. For more information about how to configure
namespace reservations, see Configuring HTTP and HTTPS. When running under Visual
Studio, the service.exe must be run with administrator privileges.
Now the service is running. Proceed to How to: Create a Windows Communication
Foundation Client. For troubleshooting information, see Troubleshooting the Getting Started
Tutorial.
See Also
Tasks
12/13/2010
Lazetti
Getting confused
There's no consistency in these examples. As a beginner in VB and WCF I couldn't get the
end of it. Could someone please post the right code? Tnx.
This is the fourth of six tasks required to create a basic Windows Communication Foundation
(WCF) service and a client that can call the service. For an overview of all six of the tasks,
see the Getting Started Tutorial topic.
This topic describes how to retrieve metadata from a WCF service and use it to create a WCF
proxy that can access the service. This task is completed by using the ServiceModel Metadata
Utility Tool (Svcutil.exe) provided by WCF. This tool obtains the metadata from the service
and generates a managed source code file for a proxy in the language you have chosen. In
addition to creating the client proxy, the tool also creates the configuration file for the client
that enables the client application to connect to the service at one of its endpoints.
Note:
You can add a service reference to your client project inside Visual Studio 2010 to create the
client proxy instead of using the ServiceModel Metadata Utility Tool (Svcutil.exe).
Caution:
When calling a WCF service from a class library project in Visual Studio 2010 you can use
the Add Service Reference feature to automatically generate a proxy and associated
configuration file. The configuration file will not be used by the class library project. You will
need to copy the configuration file to the directory that contains the executable that will call
the class library.
The client application uses the generated proxy to create a WCF client object. This procedure
is described in How to: Use a Windows Communication Foundation Client.
The code for the client generated by this task is provided in the example following the
procedure.
2. In the Add New Project dialog, select Visual Basic or Visual C#, and choose
the Console Application template, and name it Client. Use the default
Location.
3. Click OK.
Note:
When using a command-line compiler (for example, Csc.exe or Vbc.exe), you must
also provide the path to the assemblies. By default, on a computer running Windows
Vista for example, the path is: Windows\Microsoft.NET\Framework\v4.0.
VB
C#
C++
F#
JScript
Copy
using System.ServiceModel;
4. In Visual Studio, press F5 to start the service created in the previous topic. For more
information, see How to: Host and Run a Basic Windows Communication Foundation
Service.
5. Run the ServiceModel Metadata Utility Tool (Svcutil.exe) with the appropriate
switches to create the client code and a configuration file by doing the following
steps:
1. On the Start menu click All Programs, and then click Visual Studio 2010.
Click Visual Studio Tools and then click Visual Studio 2010 Command
Prompt.
2. Navigate to the directory where you want to place the client code. If you
created the client project using the default, the directory is C:\Users\<user
name>\My Documents\Visual Studio 10\Projects\Service\Client.
VB
C#
C++
F#
JScript
Copy
By default, the client proxy code is generated in a file named after the service
(in this case, for example, CalculatorService.cs or CalculatorService.vb where
the extension is appropriate to the programming language: .vb for Visual Basic
or .cs for C#). The /out switch changes the name of the client proxy file to
GeneratedProxy.cs. The /config switch changes the name of the client
configuration file from the default Output.config to App.config. Note that both
of these files get generated in the C:\Users\<user name>\My
Documents\Visual Studio 10\Projects\Service\Client directory.
6. Add the generated proxy to the client project in Visual Studio, right-click the client
project in Solution Explorer and select Add and then Existing Item. Select the
generatedProxy file generated in the preceding step.
Example
This example shows the client code generated by the ServiceModel Metadata Utility Tool
(Svcutil.exe).
VB
C#
C++
F#
JScript
Copy
//-------------------------------------------------------------------------
-----
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1366
//
// Changes to this file may cause incorrect behavior and will be lost
if
// the code is regenerated.
// </auto-generated>
//-------------------------------------------------------------------------
-----
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel",
"3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://Microsoft.S
erviceModel.Samples", ConfigurationName="ICalculator")]
public interface ICalculator
{
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Se
rviceModel.Samples/ICalculator/Add",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse"
)]
double Add(double n1, double n2);
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Se
rviceModel.Samples/ICalculator/Subtract",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResp
onse")]
double Subtract(double n1, double n2);
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Se
rviceModel.Samples/ICalculator/Multiply",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResp
onse")]
double Multiply(double n1, double n2);
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Se
rviceModel.Samples/ICalculator/Divide",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideRespon
se")]
double Divide(double n1, double n2);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel",
"3.0.0.0")]
public interface ICalculatorChannel : ICalculator,
System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel",
"3.0.0.0")]
public partial class CalculatorClient :
System.ServiceModel.ClientBase<ICalculator>, ICalculator
{
public CalculatorClient()
{
}
This is the fifth of six tasks required to create a basic Windows Communication Foundation
(WCF) service and a client that can call the service. For an overview of all six of the tasks,
see the Getting Started Tutorial topic.
This topic adds the client configuration file that was generated using the ServiceModel
Metadata Utility Tool (Svcutil.exe) to the client project and explains the contents of the client
configuration elements. Configuring the client consists of specifying the endpoint that the
client uses to access the service. An endpoint has an address, a binding and a contract, and
each of these must be specified in the process of configuring the client.
The content of the configuration files generated for the client is provided in the example after
the procedure.
address="http://localhost:8000/ServiceModelSamples/Service/Calculator
Service"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_ICalculator"
contract="Microsoft.ServiceModel.Samples.ICalculator"
name="WSHttpBinding_ICalculator">
</endpoint>
</client>
</system.serviceModel>
</configuration>
This example configures the endpoint that the client uses to access the service that is
located at the following address: http://localhost:8000/ServiceModelSamples/service
3. For more information about how to use the generated client with this configuration,
see How to: Use a Windows Communication Foundation Client.
Example
The example shows the content of the configuration files generated for the client.
Copy
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ICalculator"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
bypassProxyOnLocal="false"
transactionFlow="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxReceivedMessageSize="65536"
messageEncoding="Text"
textEncoding="utf-8"
useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32"
maxStringContentLength="8192"
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<reliableSession ordered="true"
inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows"
proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows"
negotiateServiceCredential="true"
algorithmSuite="Default"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint
address="http://localhost:8000/ServiceModelSamples/Service/CalculatorServic
e"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_ICalculator"
contract="ICalculator"
name="WSHttpBinding_ICalculator">
<identity>
<userPrincipalName value="user@contoso.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
Now the client has been configured. Proceed to How to: Use a Windows Communication
Foundation Client. For troubleshooting information, see Troubleshooting the Getting Started
Tutorial.
This is the last of six tasks required to create a basic Windows Communication Foundation
(WCF) service and a client that can call the service. For an overview of all six of the tasks,
see the Getting Started Tutorial topic.
Once a Windows Communication Foundation (WCF) proxy has been created and configured,
a client instance can be created and the client application can be compiled and used to
communicate with the WCF service. This topic describes procedures for creating and using a
WCF client. This procedure does three things:
The code discussed in the procedure is also provided in the example following the procedure.
The code in this task should be placed in the Main() method of the generated Program class
in the client project.
VB
C#
C++
F#
JScript
Copy
VB
C#
C++
F#
JScript
Copy
3. Call Close on the WCF client and wait until the user presses ENTER to terminate the
application.
VB
C#
C++
F#
JScript
Copy
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
Example
The following example shows you how to create a WCF client, how to call the operations of
the client, and how to close the client once the operation call is completed.
Compile the generated WCF client and the following code example into an executable named
Client.exe. Be sure to reference System.ServiceModel when compiling the code.
VB
C#
C++
F#
JScript
Copy
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace ServiceModelSamples
{
class Client
{
static void Main()
{
//Step 1: Create an endpoint address and an instance of the WCF
Client.
CalculatorClient client = new CalculatorClient();
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
}
}
Ensure the service is running before attempting to use the client. For more information, see
How to: Host and Run a Basic Windows Communication Foundation Service.
To launch the client, right-click Client in the Solution Explorer and choose Debug, Start
new instance.
Copy
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.
If you see this output, you have successfully completed the tutorial. This sample
demonstrates how to configure the WCF client in code. For troubleshooting information, see
Troubleshooting the Getting Started Tutorial.