Windows Communication Foundation
Module 1: Getting Started with Windows Communication Foundation
This module covers how to build a simple WCF service and client.
Module 2: Configuring and Hosting WCF Services
This module covers how to create and configure a WCF service as a managed application and select an appropriate hosting option.
Module 3: Endpoints and Behaviors
This module covers how to expose a WCF service over different endpoints and add runtime functionality using behaviors.
Module 4: Debugging and Diagnostics
This module covers how to improve debugging capabilities by examining messages and service activity.
Module 5: Designing and Defining Contracts
This module covers how to define service, operation, and data contracts to meet application requirements.
Module 6: Handling Errors
This module covers how to add error handling to a WCF application.
Module 7: Improving WCF Service Quality
This module covers how to address service quality issues such as performance, availability, concurrency and instance management.
Module 8: Implementing WCF Security
This module covers how to implement security in a WCF application.
Module 9: Implementing Transactions
This module covers how to protect data integrity through correct use of transactions.
Module 1
Getting Started with Windows Communication Foundation
Windows® Communication Foundation
(WCF) provides a unified programming model that enables you to build
distributed applications for the Microsoft® Windows operating system with
technologies such as Web services and Message Queuing (also known as MSMQ).
This module provides an overview of the WCF architecture and explains how to
implement and consume a simple WCF service by using Microsoft Visual Studio®
2008 development system.- Lesson
1: Designing an Application to be Part of a Service Oriented Architecture
(SOA)
- Lesson
2: Overview of WCF Architecture
- Lesson
3: Using a Language-Level Interface As a Service Contract
- Lesson
4: Implementing a Simple WCF Service in Visual Studio 2008
- Lesson
5: Consuming a simple WCF service in Visual Studio 2008
- Lab:
Creating a Simple Service
Lesson 1:
Designing an Application to
be Part of a Service Oriented Architecture (SOA)
Service Oriented
Architecture (SOA) is a technology-independent design philosophy that will help
you to develop powerful business-focused services that clients can access
without any knowledge of the service's implementation.
This lesson discusses
the benefits of SOA, how to design an SOA application, and how to implement a
WCF service with SOA in mind.
Benefits of Service Oriented Architecture
The primary objective of SOA is to
deliver more business benefits faster and enable your business to respond to
change, without the requirement to develop new applications from scratch.
However, to successfully use SOA
you must be aware of the following:
·
You must not make assumptions about how a
service processes a request and how a client processes a response. Services and
clients communicate only when necessary.
·
You must design loosely coupled solutions that
can tolerate changes; for example, if you use a third-party Web service in your
solution, you must ensure that your solution can run even if the third-party
Web service becomes unavailable.
·
You must design schemas and contracts that
define the functionality that your service exposes. This is because you may add
additional contracts to provide a greater level of functionality, but as long
as the service continues to implement the original contract, existing clients
will still be able to use the original functionality.
·
You must keep the non-functional requirements
such as security constraints separate from functional requirements such as the
implementation of the service.
Additional
Reading
For more information about SOA, see "Service
Oriented Architecture" on the MSDN Web site.
Designing an SOA Application
The high-level steps that you use
to design an SOA include the following:
1. Get
commitment for the major effort in architectural governance that is required to
deliver a successful SOA strategy.
2. Gather
the services by:
·
Harvesting services from projects that have been
developed in a service-aware manner.
·
Building new service interfaces for existing
functionality.
·
Having new projects build services as they go.
3. Group
related business functions together, but be mindful of granularity. Do not just
create a distributed data access layer that strongly binds clients to the
underlying schema and assumptions. Your client only needs to be aware of the
service that it wants to communicate with, not the underlying implementation.
Services can be discovered as part of the overall design and architecture of the application. Consider the following discussion that may be part of a design meeting:
Services can be discovered as part of the overall design and architecture of the application. Consider the following discussion that may be part of a design meeting:
·
"The user is then registered as a
customer…"
·
"How does the system do that?"
·
"Through the Customer Management
Service…"
·
"Okay, let's add that one to our list of
potential services."
Design Constraints
When you design an SOA, keep
business methods at the level of coarse-grained business functions instead of
at a detailed level. Each business method performs a complete, self-contained
function, be independent, and not require subsequent calls to other methods in
a specific sequence.
You can also follow a
document-centric approach to defining an SOA; for example, your client sends a
single message that contains all necessary data for the business function to
the service, as opposed to being Remote Procedural Call (RPC) centric. RPC
specifies that your client would send multiple messages containing information
to satisfy only part of the business function.
Additional
Reading
For more information about designing an SOA application, see "Principles
of Service Design: Service Patterns and Anti-Patterns" on the
MSDN Web site.
Services, Components, and Objects
Services are independent processes
defined by an interface. Services are more coarse-grained than objects or
components. Services manage their own resources and also have a lifespan and
life cycle that is independent of the applications that use them.
Components are platform-level
building blocks created for a particular platform, for example, Microsoft .NET
and Java 2 Platform Enterprise Edition (J2EE). Components are also defined by
their interface, but this is a platform-specific interface. You can think of
components as building blocks that you can plug together at design time and
compile time.
Objects are language-level
building blocks inside components and services. Objects represent relatively
fine-grained concepts such as data entities and business rules.
WCF and SOA
WCF supports SOA by providing an
easy way to expose language-level contract definitions in platform-independent
terms.
Most developers do not have to
learn technologies such as Web Service Description Language (WSDL) because the
runtime handles the majority of the "functionality." Tools such as
Visual Studio 2008 enable easy creation and consumption of WCF services.
However, just because you have exposed an interface over a Web service protocol
stack does not mean that you have created part of an SOA.
WCF plays the role of distribution
mechanism and is the technology that you can use to implement SOA, but just
because you use WCF does not mean that your solution will be service
orientated.
WCF in an SOA Context
When you design and implement a
system, you will have objects that represent business data, code for storing
and managing data, and business rules that determine how these objects
interact. A service forms a "business façade" through which clients
can invoke the business logic and manage the objects.
In the Customer Management Service
application example, at the language level you have customer details stored in
a Microsoft SQL Server® database. You then have your
business logic that can manipulate the customer details, and the business
interface that interacts with the business logic.
Alternatively, at the service
level, you have a business façade, or controller, that references more granular
operations. To the business interface, the façade provides access to complete
operations such as register customer, which in fact hooks into more granular
operations such as perform credit check and get customer details. At service
level, the business only interacts with the high-level business operations
exposed by the façade, not the individual language-level methods.
Lesson 2:
Overview of WCF
Architecture
WCF services can provide
functionality to an audience of distributed clients. WCF achieves this through
the various core concepts that make up the WCF service architecture.
This lesson describes
those core concepts, including how the service communicates messages, the
notion of ABC, the main components that make up a service, and why WCF is
considered a unified programming model.
Service-Oriented Development with WCF
Service-oriented development with
WCF consists of two steps. Firstly, create a service that exposes a set of
related functionality over a network protocol. Secondly, clients invoke any of
the methods exposed by the service to access the underlying functionality.
Client applications communicate in a very message-orientated manner by using
request messages and, potentially, response messages.
It is important to remember that
with WCF, you can communicate over many different protocols such as HTTP and
TCP.
Service-oriented development is
aimed at clients and services that do not share the same address space;
however, the client and service can, in fact, run on the same computer, not
necessarily distributed over a network.
Sending a WCF Message
A WCF service exposes multiple
endpoints, which are gateways that provide a way for other applications to
communicate with the service. Each service endpoint contains an address,
binding, and contract, which provides the client with the necessary information
to successfully communicate with the service.
The role of the WCF Dispatcher is
to determine which operation the message is for and to invoke the operation
code in the WCF service. There is a channel stack between the WCF Dispatcher
and the external environment. This stack contains the following components,
each with a specific role in the messaging process.
·
Protocol channels (such as security or
transaction control)
·
Message encoder
·
Transport channel
The channel stack implements the
policy (including security, reliable messages, and transactions) required to
communicate with the service. It is important that you order the channels
according to the function that they perform; for example, for a given binding,
at the top, you would have the transaction flow, followed by encoding, and then
the transport channel.
The client uses the proxy object
to invoke the operations exposed by the WCF service. The proxy hides the
complexity of the communication process with a remote service. The client can
invoke operations exposed by the service in the same way as the client would
invoke methods exposed by a local object.
Additional Reading
For more information about WCF
messaging, see "WCF
Messaging Fundamentals" on the MSDN Web
site.
For more information about WCF
bindings and channels, see "Windows
Communication Foundation Binding and Channels"
on the MSDN Web site.
The ABC of Endpoints
An endpoint defines the three
pieces of information that a client requires to successfully communicate with a
service; these are as follows:
·
The logical address of the service. This is a
Uniform Resource Identifier (URI) in the format required by the transport
protocol used by the service.
·
The binding policy and non-functional requirements
demanded by the service, as determined by the channel stack. WCF provides a
predefined set of bindings, but you can also define your own custom bindings.
·
The functionality exposed by the service. This
includes the names of the business methods, the parameters each method takes,
and the type of any data returned. You specify this as a service contract.
Additional
Reading
For more information about WCF endpoints, see "Endpoints:
Addresses, Bindings, and Contracts" on the MSDN Web site.
Structure of a Service
A WCF service has the following
elements:
·
The service host is a mechanism for publishing
the WCF service so that it is accessible to clients. The host can be Internet Information
Services (IIS), Windows Activation Service (WAS), or a custom .NET Framework
application.
·
The service contracts define the functionality
that the service provides in a platform-independent way; for example, a banking
service would provide operations to transfer money and query your balance.
·
The IMetadataExchange
contract enables clients to discover services. If the service implements the IMetadataExchange
contract, the service will expose a metadata exchange endpoint. You can then
use the Add Service Reference tool in Visual Studio to automatically generate a
proxy object. This feature is optional. You can generate a proxy by using the
Svcutil.exe tool without exposing a metadata exchange endpoint.
·
WCF service contracts are implemented by .NET Framework
classes and interfaces.
A Unified Programming Model
WCF provides a unified programming
model that offers all the existing functionality of existing Microsoft
distributed communication, component, and Web service technologies such as the
following:
·
ASMX
·
Component Object Model (COM)
·
COM+
·
Distributed Component Object Model (DCOM)
·
Message Queuing (also known as MSMQ)
·
Remoting
·
Web Service Enhancements (WSE)
Microsoft built WCF from scratch
to include all the preceding functionality, so that developers would no longer
have to learn many different technologies to be able to develop a distributed
system. You must still understand how each individual communication mechanism
works to ensure that you use the correct configuration.
WCF supports your solution from
end to end.
Communicating with Non-WCF Services
WCF provides the ability to
interoperate with applications developed in technologies other than WCF. WCF
achieves this through the following:
·
WCF is based on the WS-* set of standards; as
long as your other applications conform to these standards, they will be able
to communicate with your WCF service. WCF also provides simpler bindings to
interoperate with older Web service protocols such as those used by Microsoft
ASP.NET .ASMX files and other non-Microsoft Web services. You can even create a
very simple binding to support Plain Old XML (POX) services.
·
WCF provides functionality to work with legacy
applications developed in Microsoft technologies that predate WCF.
Lesson 3:
Using a Language-Level
Interface As a Service Contract
WCF enables you to use a
language-level interface as the contract in your service.
This lesson describes
the various components in a service contract and how they fit together.
Example of a Simple Contract
The Service Contract attribute identifies the interface as a WCF service
contract from which WCF can generate a Web Service Description Language (WDSL)
language. The Namespace attribute must
qualify the contract that belongs to your organizational and the functional
domain. You must distribute any changes to the Service Contract to the client; otherwise, you run the risk of clients that
send messages to your service that do not contain the necessary information.
The Operation Contract attribute specifies additional information for each
operation implemented by the service. The parameter's return value and
exceptions declared by the method annotated by the Operation Contract attribute specify the information to include in the Simple
Object Access Protocol (SOAP) messages sent back and forth. The Operation Contract attribute can also dictate some aspects of the security
policy implemented by the service for individual messages.
The following code example
illustrates a sample contract that exposes three methods.
[Visual
Basic]
Imports System
Imports
System.ServiceModel
Namespace ConnectedWCF
<ServiceContract([Namespace] :=
"http://myuri.org/Simple")> _
Public Interface IBank
<OperationContract()> _
Function GetBalance(ByVal account As String) As Decimal
<OperationContract()> _
Sub Withdraw(ByVal account As String, ByVal amount As Decimal)
<OperationContract()> _
Sub Deposit(ByVal account As String, ByVal amount As Decimal)
End Interface
End Namespace
[Visual
C#]
using System;
using
System.ServiceModel;
namespace
ConnectedWCF
{
[ServiceContract(Namespace="http://myuri.org/Simple")
]
public interface IBank
{
[OperationContract]
decimal GetBalance(string account);
[OperationContract]
void Withdraw(string account, decimal
amount);
[OperationContract]
void Deposit(string account, decimal
amount);
}
}
The ServiceContract Attribute
The ServiceContract attribute enables the WCF runtime to generate a
description for the service. Interfaces not marked with a ServiceContract attribute are not visible as WCF services and are not
accessible to WCF clients.
The namespace for a WCF service
defaults to http://tempuri.org. You can specify a more descriptive namespace by setting
the Namespace property in
the ServiceContract attribute.
Endpoints expose service contracts
to clients. If you do not publish your service contracts on an endpoint, those
contracts will be inaccessible to clients.
Additional
Reading
For more information about designing service contracts, see "Designing
Service Contracts" on the MSDN Web site.
The OperationContract Attribute
Additional
Reading
For more information about service contracts, see "Implementing
Service Contracts" on the MSDN Web site.
Data and Messages
Additional
Reading
For more information about data contracts, see "Using
Data Contracts" on the MSDN Web site.
Contracts, Metadata, and Artifacts
To consume a WCF service, you must
first know what functionality the service provides. You can use the Svcutil.exe
tool to analyze a service assembly and extract its metadata. You can then use
the metadata to create artifacts such as the proxy.
You can also use Svcutil.exe to
generate the proxy by analyzing a running WCF service, but you can do this only
if the WCF service exposes a metadata exchange endpoint.
Additional
Reading
For more information about the Svcutil.exe tool, see "ServiceModel
Metadata Utility Tool (Svcutil.exe)" Lesson 4:
Implementing a Simple WCF
Service in Visual Studio 2008
Visual Studio 2008
provides the necessary project templates and functionality for you to easily
implement a WCF service.
This lesson describes
how to define a service contract, how to implement that contract, and how to
configure and host the simple WCF service.
Defining the Service Contract and Service Class
When you create a new WCF Service
Library or WCF Service Application project, Visual Studio 2008 automatically
generates a default service contract class and a default service implementation
class.
The following code examples show
the default classes.
[Visual
Basic]
' Default
contract
<ServiceContract()>
_
Public
Interface IService1
<OperationContract()> _
Function GetData(ByVal intParam As Integer)
As String
<OperationContract()> _
Function GetDataUsingDataContract(ByVal
composite As _
CompositeType) As CompositeType
End Interface
<DataContract()>
_
Public Class
CompositeType
Private boolValueField As Boolean
Private stringValueField As String
<DataMember()> _
Public Property BoolValue() As Boolean
Get
Return Me.boolValueField
End Get
Set(ByVal value As Boolean)
Me.boolValueField = value
End Set
End Property
<DataMember()> _
Public Property StringValue() As String
Get
Return Me.stringValueField
End Get
Set(ByVal value As String)
Me.stringValueField = value
End Set
End Property
End Class
' Default
implementation
Public Class
Service1
Implements IService1
Public Sub New()
End Sub
Public Function GetData(ByVal intParam As
Integer) As String _
Implements IService1.GetData
Return String.Format("You entered:
{0}", intParam)
End Function
Public Function
GetDataUsingDataContract(ByVal composite As _
CompositeType) As CompositeType
Implements _
IService1.GetDataUsingDataContract
Return composite
End Function
End Class
[Visual
C#]
// Default
contract
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using
System.Text;
namespace
WCFService1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int intParam);
[OperationContract]
CompositeType
GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
// Default implementation
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using
System.Text;
namespace
WCFService1
{
public class Service1 : IService1
{
public string GetData(int intParam)
{
return string.Format("You
entered: {0}", intParam);
}
public CompositeType
GetDataUsingDataContract(CompositeType
composite)
{
return composite;
}
}
}
You can modify the default
contract and implementation classes to provide functionality that suits your
requirements; alternatively, you can delete them and add your own files.
Hosting the Service
The simplest way to host your
service is to create a WCF service by using the WCF Service Application
template in Visual Studio 2008.
The WCF Service Application
template is a complete simple WCF service that you can run in the same way as
any ASP.NET Web site in Visual Studio 2008.
Note: Although the
WCF Service Application template provides a complete service, it is a better
practice to define a service contract and implementation in a WCF Service
Library template and then use the WCF Service Application template to host the
service.
Visual Studio 2008 provides
development hosting on a "light" version of IIS. This enables you to
test and debug your service during development without explicitly deploying it
to IIS.
Configuring the Service
After you define your contract and
implement it, you must then configure the service so that it can communicate
with remote clients.
In the .NET Framework 3.0 and
Visual Studio 2008, Microsoft has simplified the service configuration process
by providing the WCF Service Configuration Editor. The Service Configuration
Editor tool provides a graphical user interface that enables you to modify the
configuration file for you service without writing the native XML code.
What Properties Must You Configure?
In the unlikely event that you use
a WCF Service Application project without modifying the default contract or
implementation classes, you do not have to make any changes to the default
configuration file.
However, if you change the name of
the contract from the default IService1 to something
more meaningful, you must change the contract
attribute of the endpoint element.
There are many other settings that
you can configure to adjust the way your service functions and behaves,
including the following:
·
Additional endpoints such as an endpoint with a mexHttpBinding and
matching address that would expose the service metadata.
·
Diagnostic utilities such as message logging.
·
Service behaviors options such as whether to run
your service with debugging enabled.
Additional
Reading
For more information about the WCF Service Configuration Editor tool, see
"Configuration
Editor Tool (SvcConfigEditor.exe)" on the MSDN Web site.
Demonstration: Creating a Simple Bank Service
Lesson 5:
Consuming a Simple WCF
Service in Visual Studio 2008
Visual Studio 2008
provides the necessary tools for you to create a client application that
consumes a WCF service.
This lesson explains how
to generate a proxy object that represents your WCF service and then use that
proxy object in your client application.
Importing the Metadata
To call the methods in your WCF
service, you must first create a proxy object that represents your service and
the available methods.
The Add Service Reference Function in Visual Studio 2008
Visual Studio 2008 provides the
Add Service Reference function, which enables you to generate a proxy object
just by specifying the address of the service. To use the Add Service Reference
functionality, your WCF service must expose a metadata endpoint. If it does
not, the metadata that describes your service will not be available, and Visual
Studio 2008 will not be able to generate a proxy object.
The Svcutil.exe Command-Line Tool
An alternative to the Add Service
Reference function is the Svcutil.exe command-line tool, which enables you to
manually generate a proxy class from your WCF service assembly. Typically,
after you generate the proxy by using Svcutil.exe, you then manually add the
proxy class to your client application.
For example, the following command
generates metadata for the service contracts and types from an assembly.
[Example
command]
svcutil
BankService.dll
Calling the Service by Using the Proxy
When you generate a proxy class,
you basically create a client-side class that represents the service and
service contract. You can then invoke the methods in this class as you would
with any other .NET Framework class. The proxy object hides the complexity of
the communications between a client and a service.
To use the proxy class, you must
first bring the class into scope by referencing the proxy object namespace. The
following example references the BankServiceReference
proxy class in the BankServiceClient client application.
[Visual
Basic]
Imports
BankServiceClient.BankServiceReference
[Visual
C#]
using
BankServiceClient.BankServiceReference;
You must then create an instance
of the proxy class. The following example creates a new instance of the IBank contract and passes the WSHttpBinding_IBank endpoint name as a parameter.
[Visual
Basic]
Dim proxy As
IBank = New BankClient("WSHttpBinding_IBank")
[Visual
C#]
IBank proxy =
new BankClient("WSHttpBinding_IBank");
You can then call the methods in
the proxy object as you would on any other .NET Framework object. The following
example calls the GetBalance method, which
returns a double value.
[Visual
Basic]
Dim balance As
Double = proxy.GetBalance(1234)
[Visual
C#]
double balance
= proxy.GetBalance(1234);
Demonstration: Calling the Simple Bank Service
Lab: Creating a Simple Service
Scenario
You are a developer on the
Contoso, Ltd Clinic Management product team. You start development on the
appointments service.
In this exercise, you will develop
the WCF service by using the WCF Service Library template in Visual Studio
2008. You will then define a service contract, implement the service contract,
and configure the service's endpoints. Finally, you will host the service in
Internet Information Services (IIS).
The following illustration shows the components in the appointment service
that you will implement in exercise one.
Exercise 1: Creating a Simple WCF Service
The main tasks for this exercise
are as follows:
1. Start
the 6461A-LON-DEV-01 virtual machine and log on as Student.
2. Add
a new WCF Service Library project to the existing ConnectedWCF solution.
3. Add
the existing AppointmentHelperClass
class to the solution.
4. Define
the service contract.
5. Implement
the service contract.
6. Add
a WCF Service Application project to the ConnectedWCF solution.
7. Configure
the endpoints for the AppointmentServiceIISHost.
8. Test
the Appointment service.
Note: Some of the code files in the labs for this course
include TODO comments that mark a specific point where you must make a change
to the code. Do not remove the TODO comments because other tasks that follow
may refer to them.
Task 1: Start the 6461A-LON-DEV-01
virtual machine and log on as Student
1. Open
the Virtual Server Remote Control Client, and then double-click 6461A-LON-DEV-01.
2. Log
on to 6461A-LON-DEV-01 as Student by using
the password Pa$$w0rd.
Task 2: Add a new WCF Service Library project to the existing ConnectedWCF
solution
1. Open
Microsoft
Visual
Studio
2008.
2. Open
the existing ConnectedWCF
solution. If you are using Microsoft Visual Basic® development system, browse
to the E:\Labfiles\Starter\VB\ConnectedWCF folder, and then double-click the ConnectedWCF.sln
file. If you are using Microsoft Visual C#® development tool, browse to the
E:\Labfiles\Starter\CS\ConnectedWCF folder, and then double-click the ConnectedWCF.sln
file.
3. Add
a new project with the following information to the ConnectedWCF
solution:
o Project
types: If you are using Visual Basic, expand Visual Basic, and then click WCF. If you are
using Visual C#, expand Visual
C#, and then click WCF.
o Templates:
WCF Service Library.
o Name:
AppointmentService.
o
Location: If you are using Visual
Basic, in the Location
box, type E:\Labfiles\Starter\VB\ConnectedWCF.
If you are using Visual C#, in the Location
box, type E:\Labfiles\Starter\CS\ConnectedWCF
4. Open
the Properties window for the AppointmentService
project.
5. Change
the Root namespace
(for Visual Basic) or Default
namespace
(for Visual C#) value to com.contoso.AppointmentService.
6. Save
your changes.
Task 3: Add the existing AppointmentHelperClass to the solution
1. Add
the AppointmentHelperClass
class to the AppointmentService
project:
o If
you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\ folder.
o If
you are using Visual C#, browse to the E:\Labfiles\Starter\CS\
folder.
2. In
the Code Editor window, open the AppointmentHelperClass.
The AppointmentHelperClass contains the business logic for the AppointmentService project. The logic is encapsulated in three shared (for Visual Basic) or static (for Visual C#) methods, which will enable you to retrieve all available appointment time slots from the Appointments database and book a new appointment or delete an existing appointment and update the Appointments database accordingly.
The AppointmentHelperClass contains the business logic for the AppointmentService project. The logic is encapsulated in three shared (for Visual Basic) or static (for Visual C#) methods, which will enable you to retrieve all available appointment time slots from the Appointments database and book a new appointment or delete an existing appointment and update the Appointments database accordingly.
Task 4: Define the service contract
1. Rename
the IService1 file
to AppointmentServiceContract.vb
(for Visual Basic) or AppointmentServiceContract.cs
(for Visual C#).
2. In
the Code Editor window, open the AppointmentServiceContract
class.
3. If
you are using Visual C#, in the Code Editor window, change the namespace to com.contoso.AppointmentService.
4. If
you are using Visual C#, change the interface name to AppointmentServiceContract.
5. Remove
the following from the AppointmentServiceContract
class:
o All
comments
o The
CompositeType
class definition
o The
GetData
and GetDataUsingDataContract
methods in the AppointmentServiceContract
interface definition
6. Modify
the ServiceContract
attribute on the AppointmentServiceContract
definition to include the namespace http://contoso.com/services/AppointmentService.
7. In
the AppointmentServiceContract
definition, define a method named CreateAppointment
that returns a string
and that accepts a string
parameter named patientId, a string
parameter named doctorId, and a DateTime
parameter named start.
8. Add
the OperationContract
attribute to the CreateAppointment
method.
9. Define
a second method named CancelAppointment
that returns a bool
value and that accepts a string
parameter named appointmentId.
10. Add the OperationContract
attribute to the CancelAppointment
method.
11. Define a
third method named ListAvailableAppointmentTimes
that returns a generic List
of type DateTime
and accepts a string
parameter named doctorId and a DateTime
parameter named day.
12. Add the OperationContract
attribute to the ListAvailableAppointmentTimes
method.
Task 5: Implement the service contract
1. Rename
the Service1
class to AppointmentServiceImplementation.vb
(for Visual Basic) or AppointmentServiceImplementation.cs
(for Visual C#).
2. In
the Code Editor window, open the AppointmentServiceImplementation
class.
3. If
you are using Visual C#, in the Code Editor window, change the namespace to com.contoso.AppointmentService.
4. If
you are using Visual C#, rename the Service1
class definition to AppointmentServiceImplementation.
5. Remove
the following from the AppointmentServiceImplementation
class:
o All
comments
o The
GetData
and GetDataUsingDataContract
methods
6. Implement
the AppointmentServiceContract
interface instead of the IService1
interface, and then generate the default method stubs.
7. If
you are using Visual C#, remove the throw
new NotImplementedException(); code
from each of the three methods.
8. In
the CreateAppointment
method, add code to do the following:
o Create
an Appointment
object named newAppointment.
Use the variables patientId,
doctorId,
and start
as parameters.
o Return
the result of the static GenerateNewAppointment
method in the AppointmentHelperClass
class. Use the newAppointment object as a parameter.
9. In
the CancelAppointment
method, add code to return the result of the static CancelExistingAppointment method
in the AppointmentHelperClass
class. Use the appointmentId
variable as a parameter.
10. In the ListAvailableAppointmentTimes method,
add code to return the result of the static GetAvailableAppointments method in
the AppointmentHelperClass
class. Use the doctorId
and day
variables as parameters.
11. Build ONLY the AppointmentService project.
Task 6: Add a WCF Service Application
project to the ConnectedWCF solution
1. Add
a new project to the ConnectedWCF
solution with the following information:
o Project
types: If you are using Visual Basic, expand Visual Basic, and then click Web. If you are
using Visual C#, expand Visual
C#, and then click Web.
o Templates:
WCF Service
Application.
o Name:
AppointmentServiceIISHost.
o
Location: If you are using Visual
Basic, in the Location
box, type E:\Labfiles\Starter\VB\ConnectedWCF.
If you are using Visual C#, in the Location
box, type E:\Labfiles\Starter\CS\ConnectedWCF
2. Open
the Properties window for the AppointmentServiceIISHost
project.
3. In
the Properties window, on the Web
tab, in the Servers section,
click Specific port,
and then in the corresponding box, type 8001
4. Save
your changes.
5. If
you are using Visual Basic, in Solution Explorer, click Show All Files.
6. Remove
the following files and folders from the AppointmentServiceIISHost
project:
o The IService1 class
file
o The
Service1.svc.vb file (for Visual Basic) or the Service1.svc.cs file(for Visual
C#)
o The App_Data folder
7. Add
a reference to the AppointmentService
assembly.
8. Rename
the Service1.svc file
to AppointmentService.svc.
9.
Open AppointmentService.svc in the markup
view.
10. In the
Code Editor window, make the following changes to the ServiceHost
element in
the
AppointmentService.svc file:
o Change
the Service
attribute value to com.contoso.AppointmentService.AppointmentServiceImplementation.
o Remove
the CodeBehind
attribute and value.
11. Save your
changes.
12. Build the AppointmentServiceIISHost
project.
Task 7: Configure the endpoints for the
AppointmentServiceIISHost
1. In
the Edit WCF Configuration
window, in the AppointmentServiceIISHost project, open the
Web.config file.
Note: To open the Edit WCF Configuration window, right-click
the configuration file that you want to edit, and then click Edit WCF Configuration.
2. In
the Microsoft Service Configuration Editor window, perform the following steps:
1. Rename
the existing service behavior to AppointmentServiceIISHost.ServiceBehavior.
2. Rename
the service to com.contoso.AppointmentService.AppointmentServiceImplementation.
3. Change
the Contract
property for the wsHttpBinding
service endpoint to com.contoso.AppointmentService.AppointmentServiceContract.
Note: You can find the service behavior configuration under the
Advanced node.
3. Save
your changes, and then close the Microsoft Service Configuration Editor window.
Task 8: Test the Appointment service
1. In
Solution Explorer, right-click the AppointmentServiceIISHost
project, point to Debug,
and then click Start
new instance.
2. In
the Debugging Not
Enabled dialog box, click OK.
3. In
the Script Debugging
Disabled dialog box, click Yes.
4. In
the Information Bar
dialog box, click Close.
5. In
Windows Internet Explorer®, on the Directory
Listing
page, click AppointmentService.svc.
6. If
you have successfully configured and hosted the AppointmentService, Internet Explorer
will display the AppointmentServiceImplementation
Service default page.
7. Close
Internet Explorer.
|
Results: After this exercise, you
should have developed a WCF service in Visual Studio 2008.
|
Exercise 1: Answer Key (detailed steps)
Exercise 2: Calling the Simple WCF Service
In this exercise, you will add
code to the existing ClinicAdminClient Windows Forms application to enable
users to find all the available appointment timeslots, create a new appointment,
and delete an existing appointment.
The main tasks for this exercise
are as follows:
1. Add
a reference to the AppointmentService.
2. Add
code to the ClinicAdminClient
class.
3. Build
and run the solution.
Task 1: Add a reference to the
AppointmentService
1. In
the ClinicAdminClient project, open the ClinicAdminForm
class in the Designer window.
The ClinicAdminForm class contains the user interface that you will use to interact with the AppointmentService. In the tasks that follow, you will add a service reference and the necessary code to call the methods that the AppointmentService exposes.
The ClinicAdminForm class contains the user interface that you will use to interact with the AppointmentService. In the tasks that follow, you will add a service reference and the necessary code to call the methods that the AppointmentService exposes.
2. Add
a service reference by using the following information:
a. Address:
In the Address
box, type http://localhost:8001/AppointmentService.svc
and then click Go.
b. Namespace:
In the Namespace
box, type AppointmentServiceReference
Task 2: Add code to the ClinicAdminClient
class
1. In
the Code Editor window, open the ClinicAdminForm
class.
2. Locate
the TODO 1
comment, and then bring the ClinicAdminClient.AppointmentServiceReference
into scope.
3. Locate
the TODO 2
comment, and then add code to return a new AppointmentServiceContractClient
object.
4. Locate
the TODO 3
comment, and then add code to do the following:
o Create
a new AppointmentServiceContract
object named proxy,
and then initialize it to the return value of the GetAppointmentServiceProxy
method.
o Set
the slots
object to the return value of the ListAvailableAppointmentTimes
method in the proxy
class. Use the text
property of the doctorId
field and the value
property of the dateRequested
field as parameters.
5. Locate
the TODO 4
comment, and then add code to do the following:
o Create
a new AppointmentServiceContract
object named proxy,
and then initialize it to the return value of the GetAppointmentServiceProxy
method.
o Set
the appointmentId
variable to the return value of the CreateAppointment
method in the proxy
class. Use the text
property of the patientId
field, the text
property of the doctorId
field, and the slot
variable as parameters.
6. Locate
the TODO 5
comment, and then add code to do the following:
o Create
a new AppointmentServiceContract
object named proxy,
and then initialize it to the return value of the GetAppointmentServiceProxy
method.
o Set
the cancelled variable
to the return value of the CancelAppointment
method in the proxy
class. Use the text
property of the appointmentId
field as a parameter.
Task 3: Build and run the solution
1. Build
the ConnectWCF solution.
2. Run
the ConnectWCF solution
with debugging.
3. On
the Clinic
Administration Client form, on the Create Appointment tab,
click Find
Slots.
4. Create
an appointment with the following information, and then click Create:
o Doctor:
In the Doctor
list, click ENT_Davies.
o Date:
In the Date
list, click 30th
October 2007.
o Slots:
In the Slots
list, click any of the available time slots.
o Patient:
In the Patient
box, type your name.
5. In
the Appointment
Created dialog box, make a note of the Appointment identifier, and
then click OK.
6. On
the Cancel
Appointment tab, in the App
ID box, type your Appointment
identifier,
and then click Delete.
7. In
the Appointment
Cancellation dialog box, click OK.
8. In
Visual Studio 2008, on the Debug
menu, click Stop
Debugging.
9. Close
Visual Studio 2008.
|
Results: After this exercise, you
should have enhanced the existing ClinicAdminClient application to invoke the
methods in the AppointmentService.
|
Exercise 2: Answer Key (detailed steps)
Module 2
Configuring and Hosting WCF Services
For a client to use your Windows®
Communication Foundation (WCF) service, you must choose an appropriate WCF
hosting environment, provide the hosting environment with the necessary WCF
configuration information, and finally deploy the WCF service to an operational
platform.
This module discusses the
different hosting options available and how to host your WCF service in them.
This module also discusses the different ways that you can store WCF
configuration settings.
- Lesson 1: Programmatically Configuring a Managed
Application to Host a WCF Service
- Lesson 2: Programmatically Configuring a Managed
Application to Call a WCF Service
- Lesson 3: Defining Client and Service Settings by
Using File-Based Configuration
- Lesson 4: Selecting a Hosting Option for a WCF
Service
- Lesson 5: Deploying a WCF Service
- Lab: Configure and Host a WCF Service
·
Lesson 1:
·
Programmatically Configuring a Managed
Application to Host a WCF Service
·
·
There are a number of
ways that you can host your WCF services. You can use Internet Information
Services (IIS), Windows Activation Services (WAS), and self-host managed applications
such as a Windows console or a Windows service.
·
This lesson explains how
to host your WCF service in a self-host managed application.
Hosting a WCF Service in a Self-Hosted Managed Application
You can host your WCF service in a
number of ways, such as in:
·
A custom managed application.
·
Internet Information Services (IIS).
·
Windows Activation Services (WAS).
Hosting your WCF service in a
self-hosted managed application requires a small amount of additional code and
the necessary WCF configuration.
You can use the project templates
in Microsoft® Visual Studio® 2008 development system to develop one of the
following self-hosted applications:
·
A simple EXE to run on the command line
·
A Windows service to run constantly or on
schedule
·
A Windows Forms or Windows Presentation
Foundation (WPF) client application, which enables you to provide additional
functionality such as callbacks.
Additional Reading
For more information about hosting
WCF services, see "Hosting
Services" on the MSDN Web site.
Separation of Concerns in a WCF Service
The separation of concerns is one
of the basic tenets of good software design. Taking this approach helps
individual software elements to remain flexible and maintainable as the overall
system evolves. When you develop WCF services, some may be small, some may be
large, and some may start small and grow large over time. In addition, you do
not know how the requirements on your service will change over time. In the
future, a service that started as an intranet service could be exposed over the
Internet. In most of these cases, if the service implementation, contract, and
hosting environment are all tightly bound together, it will make such changes
far more difficult to implement.
For a simple WCF service, the WCF
Service Application template is sufficient. However, because all the service
components are stored in the same project, anything more than a simple WCF
service will lead to bloating and tight coupling between the components; for
example:
·
The contract gets lost in implementation details.
·
The contract is tied to that one implementation.
·
The service is tied to that one hosting environment.
The best approach is to keep the
components and their constituent parts separated. The WCF Service Application
template conforms to some best practices in that it keeps the contract in a
separate file from the implementation. However, in most real-world projects, you
would want to keep the host and service in separate assemblies.
You can use the WCF Service
Library project type to store the interface and implementation for the service
and then use a WCF Service Application project to store host-specific details.
An Example Contract
This is an example WCF service
contract that exposes three methods. You saw this contract exposed through an
IIS-based service host in Module 1 "Getting Started with Windows
Communication Foundation."
[Visual
Basic]
<ServiceContract([Namespace] :=
"http://myuri.org/Simple")> _
Public Interface IBank
<OperationContract()>
_
Function GetBalance(ByVal account As String) As Decimal
<OperationContract()> _
Sub Withdraw(ByVal account As String, ByVal amount As Decimal)
<OperationContract()> _
Sub Deposit(ByVal account As String, ByVal amount As Decimal)
End Interface
End
Namespace
[Visual
C#]
namespace ConnectedWCF
{
[ServiceContract(Namespace="http://myuri.org/Simple") ]
public interface IBank
{
[OperationContract]
decimal GetBalance(string account);
[OperationContract]
void Withdraw(string account, decimal amount);
[OperationContract]
void Deposit(string account, decimal amount);
}
}
An Example Service Implementation
This is an example WCF service
class that implements the IBank contract. Again,
you saw this in Module 1 "Getting Started with Windows Communication
Foundation."
[Visual
Basic]
Implements IBank
Public Function GetBalance(ByVal account As String) As Decimal
' Get it from the
database
End Function
Public Sub Withdraw(ByVal account As String, ByVal amount As _
Decimal)
' Decrease the amount in the database.
End Sub
Public Sub Deposit(ByVal account As String, ByVal amount As _
Decimal)
' Increase the amount in the database.
End Sub
End Class
End
Namespace
[Visual
C#]
namespace ConnectedWCF
{
public class BankService : IBank
{
public
decimal GetBalance(string account)
{
// Get it from the database.
}
public void Withdraw(string account, decimal
amount)
{
// Decrease the amount in the database.
}
public void Deposit(string account, decimal
amount)
{
// Increase the amount in the database.
}
}
}
An Example Self-Hosted WCF Service
You can develop your own self-host
managed application with a small amount of code. The following Windows console
application example shows you the objects that you must create and the methods
that you must call.
In following example, the address
is a combination of the base address http://localhost:8000/Simple and a
relative element, the binding is a new instance of BasicHttpBinding, and the contract is ConnectedWCF.IBank.
[Visual
Basic]
Sub Main()
Dim baseAddress As
New Uri("http://localhost:8000/Simple")
Dim instanceType As Type = GetType(ConnectedWCF.BankService)
Dim host As New ServiceHost(instanceType, baseAddress)
Using host
Dim contractType As
Type = GetType(ConnectedWCF.IBank)
Dim relativeAddress As String = "BankService"
host.AddServiceEndpoint(contractType, _
New BasicHttpBinding(), relativeAddress)
host.Open()
Console.WriteLine("Press <ENTER> to quit.")
Console.ReadLine()
host.Close()
End Using
End Sub
End Class
[Visual
C#]
public class BankServiceHost
{
public static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/Simple");
Type instanceType = typeof(ConnectedWCF.BankService);
ServiceHost host = new ServiceHost(instanceType,
baseAddress);
using (host)
{
Type contractType = typeof(ConnectedWCF.IBank);
string relativeAddress = "BankService";
host.AddServiceEndpoint(contractType,
new BasicHttpBinding(), relativeAddress);
host.Open();
Console.WriteLine("Press <ENTER> to quit.");
Console.ReadLine();
host.Close();
}
}
}
Life Cycle of a Self-Hosted WCF Service
When you develop a self-hosted application
such as a Windows service or EXE application, there is a distinct sequence that
your code will follow.
The steps in the life cycle of a
typical self-hosted WCF service include the following:
1. Initialize
the ServiceHost
and pass the service implementation type and base address information.
2. Open
the ServiceHost
to start listening.
3. Stop
the self-host application from closing. A Windows service will continue to run
through the service management system, and a graphical user interface (GUI)
application will continue to run by its user interface (UI) thread.
4. A
message arrives for the service. The service host creates an instance of the
service implementation to handle the client request.
5. After
the instance handles the message, the service host disposes of that service
instance.
6. When
the self-host application exits, you must close and dispose of the ServiceHost
object.
Note: that this life cycle differs slightly for different
service life cycle policies such as singleton services. In this case, you use a
single service implementation instance to initialize the service host. This
single service implementation instance handles all calls to the service, and
the service host does not instantiate any other service implementation
instances. You will see more about singleton services and other life cycle
management policies in Module 7.
Demonstration: Creating and Configuring a Self-Hosted WCF Service
Lesson 2:
Programmatically
Configuring a Managed Application to Call a WCF Service
When you have hosted
your WCF service, you can then create a client application to invoke the
exposed operations.
This lesson examines the
use of programmatic configuration in a WCF client, which includes what a client
must do before it can use a WCF service, how a client can obtain the necessary
artifacts, and how you use a proxy object.
Prerequisites for Calling a WCF Service from a Client
For a client to successfully call
a WCF service, the client must satisfy the following prerequisites:
·
A channel stack that enables the client to pass
messages to the service. The channel stack includes individual channels that
define the characteristics of the binding, for example, the security
constraints and transactional requirements. WCF includes predefined bindings
such as BasicHttpBinding
that define the characteristics of the channels in the channel stack.
·
A client-side representation of the contract
that enables the client to identify the operations that the WCF service
provides.
·
A proxy object that hides the complexity of
creating WCF messages to pass to the channel and provides a way of retrieving
the contents of response messages.
·
An address for the WCF service to which you send
the request messages.
Obtaining Service Information
A client application can satisfy
the prerequisites outlined in the previous topic by using service metadata.
The service metadata describes the
WCF service; this includes information about the operations that it exposes and
the types used by those operations. You can expose service metadata directly to
the client by configuring a Web Service Metadata Exchange endpoint that
implements the IMetaDataExchange
contract.
If your WCF service exposes a Web
Service Metadata Exchange endpoint, you can use tools such as the Add Service
Reference function in Visual Studio 2008 to create the necessary WCF types and
satisfy the remaining prerequisites.
Alternatively, you can manually
satisfy the prerequisites by obtaining the information and artifacts from the
service provider. The information exchange will include the following:
·
Endpoint address(es)
·
Binding(s) to be used
·
Contract type as a .NET interface
The service provider can deliver
these in several ways. They can deliver the original service contract as an
annotated .NET interface together with written instructions about which
bindings and endpoints to use. Alternatively, they can deliver metadata
documents such as Web Service Description Language (WSDL) and XML Schema
Definition (XSD). The client can use Svcutil.exe to process the artifacts and
generate client-side proxy types. A third alternative is for the service
provider to deliver a pregenerated client proxy that can just be included in
the client's project.
Using WCF Service Proxies
A client application uses a proxy
object to communicate with your WCF service. If you use a tool such as the Add
Service Reference function in Visual Studio 2008 or the Svcutil.exe
command-line tool, it will create a proxy class type that you can instantiate
directly.
[Visual
Basic]
' Bring the
namespace into scope.
Imports BankServiceReference
' Create a new
instance of the proxy class.
Dim proxy As IBank = New
BankServiceClient()
' Invoke the
methods in the proxy object.
Dim balance As Decimal =
proxy.GetBalance("ABC123")
[Visual
C#]
// Bring the
namespace into scope.
using BankServiceReference;
// Create a new
instance of the proxy class.
IBank proxy = new
BankServiceClient();
// Invoke the
methods in the proxy object.
decimal balance =
proxy.GetBalance("ABC123");
Alternatively, you can use the ChannelFactory class to provide you with an instance of a proxy that
handles a given service contract type. In this case, you must provide more of
the information that a directly instantiated proxy would obtain from the
configuration file. The following code illustrates this.
[Visual
Basic]
' Create a new
EndpointAddress object.
Dim address As
New _
EndpointAddress("http://localhost:8000/Simple/BankService")
' Create a new
binding object.
Dim binding As
New BasicHttpBinding()
' Create a
proxy object by using the contract, binding, and address objects.
Dim proxy As IBank _
= ChannelFactory(Of IBank).CreateChannel(binding, address)
[Visual
C#]
// Create a new
EndpointAddress object.
EndpointAddress address
= new
EndpointAddress("http://localhost:8000/Simple/BankService");
// Create a new
binding object.
BasicHttpBinding binding = new
BasicHttpBinding();
// Create a
proxy object by using the contract, binding, and address objects.
IBank proxy =
ChannelFactory<IBank>.CreateChannel(binding, address);
When you use the ChannelFactory class to create the proxy, you can see the ABC of the
endpoint more explicitly, with the address, binding, and contract objects.
Additional ReadingFor more information about WCF proxies, see the "Service Proxies" section in "Hosting and Consuming WCF Services" on the MSDN Web site.
For more information about the inner workings of client-side proxies, see "Client Architecture" on the MSDN Web site.
Demonstration: Creating and Configuring a Client for a WCF Service
Lesson 3:
Defining Client and Service
Settings by Using File-Based Configuration
To run a WCF solution,
your service and client require WCF configuration information. You can provide
this configuration information either programmatically or in an external
configuration file.
This lesson explains how
to use an external configuration file to store your WCF configuration.
File-Based Configuration
You can define the configuration
for your WCF client application or WCF service programmatically by using the
various classes in the System.serviceModel
namespace; for example, the EndpointAddess and ChannelFactory classes. Programmatic configuration offers greater control
over your WCF configuration; however, any changes that you make to the
configuration require recompilation of the assembly.
Hardcoding this type of
configuration also assumes that the developer knows all the circumstances in
which the service and client will run.
Alternatively, you can define the
WCF configuration for your WCF service or client in a standard .NET Framework
configuration file such as an App.config, Web.config, or Machine.config file.
File-based configuration is more flexible because you can change the WCF
configuration without recompiling the assembly.
Anything
that must be enforced can be kept at code or contract level; for example, threading and instance management.
If
your solution uses both programmatic and file-based
configuration, the programmatic configuration takes precedence.
Additional ReadingFor more information about file-based configuration, see "Configuring Services Using Configuration Files" on the MSDN Web site.
Identifying WCF Entries in Configuration Files
A typical WCF configuration file
will contain the following elements:
·
<service> element. This defines one or more <service> elements contained in <services>
in addition to <host> and <endpoint> information about the service.
·
<endpoint> element. This defines the address, binding, and contract.
·
<host> element. This defines base addresses and timeouts.
Additional ReadingFor more information about the elements in a WCF configuration file, see "<system.serviceModel>" on the MSDN Web site.
For more information about how the different elements fit together in a WCF configuration file, see "Windows Communication Foundation Configuration Schema" on the MSDN Web site.
Demonstration: File-Based Configuration
Selecting a Hosting Option
for a WCF Service
To make your WCF service
available to clients, you must house the service in a hosting environment.
There are several options that you can choose from, each with its own benefits
and disadvantages.
This lesson discusses
the different options available and how you can use them.
Hosting a WCF Service
To successfully expose your WCF
service, you must host it. So far in this course, the lab exercises and
demonstrations have used either the Visual Studio 2008 development environment,
which in essence uses a lightweight version of IIS, or a custom managed
self-hosted application.
A hosting environment must provide
the following functionality for your WCF service:
·
Read and interpret WCF configuration settings.
You have seen the schema used by WCF to store the settings that define the
characteristics of a service such as its endpoints. You do not want to have to
implement code to read and work with these configuration settings.
·
Expose the service over the endpoints defined in
the WCF configuration, and then listen for requests from remote clients over
these endpoints.
·
Route messages sent from clients over a
particular endpoint to an appropriate service instance.
·
Manage the creation and destruction of service
instances to prevent unnecessary usage of system resources.
Depending on the hosting
environment, the environment may also provide the following additional
functionality:
·
Isolate different service instances from each
other, which helps to keep exceptions isolated to a particular service
instance. For example, if a
service host has a single application domain, an unhandled exception could affect all service instances.
·
Serialize and reactivate unused service
instances.
·
Manage precreated pools of service instances.
Service Hosting Options
There are three main hosting
options that you can choose from. These are:
·
Self-hosted
managed application, such as a Windows console EXE, Windows service, or a WPF application.
·
Host under IIS.
·
Host by using Windows Activation Service (WAS), which comes with IIS and enables
hosting on protocols other than Hypertext Transfer Protocol (HTTP) such as TCP.
All of these options provide the
basic functionality described in the previous topic.
Hosting your WCF service in IIS
and WAS offers the following improved benefits over self-hosted managed
applications:
·
Message
based activation, which creates a new instance of the service when a message
arrives, rather than having a service run constantly.
·
Process
recycling, which restarts the hosting process to clear the effects of memory
leaks.
·
Idle
shutdown, which stops and serializes the service after a given time to
conserve system resources.
·
Process
health monitoring, which enables you to respond to resources issues in
the services.
Additional ReadingFor more information about the possible hosting options, see "Hosting and Consuming WCF Services" on the MSDN Web site.
Implementing a Self-Hosted Service
Self-hosted service applications
enable you to develop a custom host for your WCF service that provides only the
functionality that you require.
A self-hosted application enables
you to manually control the activation and hosting of your WCF service. For
example, you can have a WPF self-host application with controls that enable you
to start and stop the service host.
To implement your own self-hosted
service application, you must write code to do the following:
·
Instantiate a ServiceHost for your service type.
·
Add one or more endpoints.
·
Open the ServiceHost
to listen for connections.
Similar to hosting your WCF
service with IIS, you must provide some WCF configuration such as the endpoint
ABC. You can provide this configuration either programmatically or in an
external configuration file.
Self-hosted service applications
do not restrict you to just the HTTP-based protocols in the way that IIS does.
For example, you can expose your WCF service over a TCP protocol if required.
With self-hosted service
applications, you can also add additional code to provide greater control over
your WCF service and information about the current state of the service host.
The following code shows how you
can respond to the Opened, Closing, Closed, and Faulted events of the ServiceHost
class.
[Visual
Basic]
' Create a
ServiceHost object.
Dim host As New
ServiceHost(instanceType)
' Register the
events.
AddHandler
host.Opened, AddressOf host_Opened
AddHandler
host.Closing, AddressOf host_Closing
AddHandler
host.Closed, AddressOf host_Closed
AddHandler
host.Faulted, AddressOf host_Faulted
' Open the
host.
host.Open()
...
' Respond to
the events.
Sub
host_Closed(ByVal o As Object, ByVal e As EventArgs)
' Response.
End
Sub
Sub
host_Closing(ByVal o As Object, ByVal e As EventArgs)
' Response.
End
Sub
Sub
host_Opened(ByVal o As Object, ByVal e As EventArgs)
' Response.
End
Sub
Sub
host_Faulted(ByVal o As Object, ByVal e As EventArgs)
' Response.
End
Sub
[Visual
C#]
// Create a
ServiceHost object.
ServiceHost
host = new ServiceHost(instanceType);
// Register the
events.
host.Opened
+=new EventHandler(host_Opened);
host.Closing
+=new EventHandler(host_Closing);
host.Closed
+= new EventHandler(host_Closed);
host.Faulted
+=new EventHandler(host_Faulted);
// Open the
host.
host.Open();
...
// Respond to
the events.
static
void host_Closed(object o, EventArgs e)
{
// Response.
}
static
void host_Closing(object o, EventArgs e)
{
// Response.
}
static
void host_Opened(object o, EventArgs e)
{
// Response.
}
static
void host_Faulted(object o, EventArgs e)
{
// Response.
}
Hosting in a Windows Service
You can also host your WCF service
in a Windows service. Windows services provide the benefits of being able to
activate and start your WCF service as soon as the system boots up and run
silently in the background.
To create your own custom Windows
service, you derive your service class from the ServiceBase class. You can then override the event methods OnStart and OnStop and add code to
start and stop your WCF service with the methods on the ServiceHost class.
The following example shows a
typical implementation of the OnStart and OnStop methods.
[Visual
Basic]
' OnStart
method implementation.
Protected
Overloads Overrides Sub OnStart(ByVal args As String())
Dim serviceType As Type =
GetType(TradeService)
' host is an instance variable of type
ServiceHost.
host = New ServiceHost(serviceType)
host.Open()
End Sub
' OnStop method
implementation.
Protected
Overloads Overrides Sub OnStop()
If host = Nothing Then
host.Close()
host = Nothing
End If
End Sub
[Visual
C#]
// OnStart
method implementation.
protected
override void OnStart(string[] args)
{
Type serviceType = typeof(TradeService);
// host is an instance variable of type
ServiceHost.
host = new ServiceHost(serviceType);
host.Open();
}
// OnStop
method implementation.
protected
override void OnStop()
{
if (host != null)
{
host.Close();
host = null;
}
}
When you have created your Windows
service, you then must create an installer that installs the Windows service on
your target computer. You can create an installer by using the Setup Project
template in Visual Studio 2008.
You can control the life cycle of
your Windows service with the Management Console Services snap-in.
Additional ReadingFor more information about hosting your WCF service in a Window Service, see "How to: Host a WCF Service in a Managed Windows Service" on the MSDN Web site.
Implementing an IIS-Hosted Service
IIS provides a robust hosting
environment that you can use to host your WCF services, although IIS does limit
you to the HTTP protocol.
You can create an IIS host project
for your WCF service by using the WCF Service Application project template in
Visual Studio 2008. This project template contains the necessary configuration
file to hold your WCF configuration and the .svc file that contains the ServiceHost directive.
The following example shows a .svc
file.
[Visual
Basic]
<%@ServiceHost language=c#
Service="ConnectedWCF.BankService">
[Visual
C#]
<%@ServiceHost language=vb
Service="ConnectedWCF.BankService">
In its simplest form, if you use
the WCF Service Application project template, you can keep the service contract
and implementation in the same project in the App_Code subdirectory. However,
the best method is to keep the WCF Service Application project just for the
configuration file and .svc file, and then add a reference to a WCF Service Library
project that contains your service contract and implementation.
Additional ReadingFor more information about hosting your WCF service in IIS, see "How to: Host a WCF Service in IIS" on the MSDN Web site.
Implementing a WAS-Hosted Service
WAS is another alternative hosting
option to IIS and self-host applications. Hosting with WAS shares the following
similarities with hosting in IIS:
·
You do not have to write any additional host-specific
code.
·
You store the WCF configuration in an external
configuration file.
·
You must provide a .svc file that contains the ServiceHost
directive.
·
You must place your WCF service in an IIS
application folder.
WAS does not require your WCF
service to run continually. When a message arrives, WAS will create a service
instance accordingly.
The main advantage of WAS over IIS
is that you can use protocols other than HTTP such as TCP.
Additional ReadingFor more information about hosting your WCF service in WAS, see "How to: Host a WCF Service in WAS" on the MSDN Web site.
Configuring WAS
To host your WCF with WAS, you
must turn on the Windows Non-Http Activation Components on your host computer.
You can do this through the Turn Windows features on or off function.
You must also bind the desired Web
site to a non-HTTP port to support the non–HTTP–based activation. The following
example shows you how to bind the Default Web Site to a non-HTTP port by using
the appcmd command-line tool that is installed with IIS 7.
[appcmd
example]
appcmd set site "Default Web
Site"-+bindings.[protocol='net.tcp',bindingInformation='9000:*']
You can also bind a specific Web
application to a non-HTTP port. The following example illustrates this.
appcmd set app "Default Web
Site/BankService"
/enabledProtocols:http,net.tcp,net.pipe
If you run the appcmd tool, it will modify the IIS 7 configuration setting in
the applicationHost.config
file in the C:\Windows\System32\inetsrv\config
folder.
When you have enabled a non-HTTP
protocol such as TCP, if you want to define an endpoint that uses the protocol,
you must substitute http for net.tcp in the endpoint address. The following example illustrates
this.
[Example
tcp endpoint address]
address="net.tcp://localhost/BankService/BankServiceIISHost.svc"
Additional ReadingFor more information about configuring the WCF activation components, see "How to: Install and Configure WCF Activation Components" on the MSDN Web site.
Implementing a WAS-Hosted Service
WAS is another alternative hosting
option to IIS and self-host applications. Hosting with WAS shares the following
similarities with hosting in IIS:
·
You do not have to write any additional
host-specific code.
·
You store the WCF configuration in an external
configuration file.
·
You must provide a .svc file that contains the ServiceHost
directive.
·
You must place your WCF service in an IIS
application folder.
WAS does not require your WCF
service to run continually. When a message arrives, WAS will create a service
instance accordingly.
The main advantage of WAS over IIS
is that you can use protocols other than HTTP such as TCP.
Additional ReadingFor more information about hosting your WCF service in WAS, see "How to: Host a WCF Service in WAS" on the MSDN Web site.
Configuring WAS
To host your WCF with WAS, you
must turn on the Windows Non-Http Activation Components on your host computer.
You can do this through the Turn Windows features on or off function.
You must also bind the desired Web
site to a non-HTTP port to support the non–HTTP–based activation. The following
example shows you how to bind the Default Web Site to a non-HTTP port by using
the appcmd command-line tool that is installed with IIS 7.
[appcmd
example]
appcmd set site "Default Web
Site"-+bindings.[protocol='net.tcp',bindingInformation='9000:*']
You can also bind a specific Web
application to a non-HTTP port. The following example illustrates this.
appcmd set app "Default Web
Site/BankService"
/enabledProtocols:http,net.tcp,net.pipe
If you run the appcmd tool, it will modify the IIS 7 configuration setting in
the applicationHost.config
file in the C:\Windows\System32\inetsrv\config
folder.
When you have enabled a non-HTTP
protocol such as TCP, if you want to define an endpoint that uses the protocol,
you must substitute http for net.tcp in the endpoint address. The following example illustrates
this.
[Example
tcp endpoint address]
address="net.tcp://localhost/BankService/BankServiceIISHost.svc"
Additional ReadingFor more information about configuring the WCF activation components, see "How to: Install and Configure WCF Activation Components" on the MSDN Web site.
No comments:
Post a Comment