10263A ENU Companion
10263A ENU Companion
10263A
Developing Microsoft® Windows
Communication Foundation Solutions with
Microsoft Visual Studio® 2010
Companion Content
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
© 2010 Microsoft Corporation. All rights reserved.
Released: 08/2010
Service-Oriented Architecture 1-1
Module 1
Service-Oriented Architecture
Contents:
Lesson 1: What Is SOA? 2
Lesson 2: The Benefits of SOA 5
Lesson 3: Scenarios and Standards 8
Module Reviews and Takeaways 11
Lab Review Questions and Answers 12
1-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
What Is SOA?
Contents:
Question and Answers 3
Additional Reading 4
Service-Oriented Architecture 1-3
Answer: When a service is used without concern to boundaries, performance can be impaired. For
example, if a service is called in a loop many times to add many entities to a database, boundaries are
crossed often, and this could have a performance hit on your application. To reduce the number of
times the boundary is crossed you can, for example, create another service operation that receives a
bulk of entities, and adds all of them to the database – this way the boundary is crossed only once
instead of numerous times. Understanding the concept of boundaries and implementing it in your
service design can improve the way your client and service interact and the overall performance of
your system.
1-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
The Pillars of SOA
For more information about Service-Oriented Architecture, see the Understanding Service-Oriented
Architecture page on the Microsoft website.
Service-Oriented Architecture 1-5
Lesson 2
The Benefits of SOA
Contents:
Question and Answers 6
Additional Reading 7
1-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: When a new operation is introduced to a contract, clients which are not aware of the change
will most probably not be affected by the change, since none of the messages they send hold
requests for the new operation. However, changing the signature of an existing operation can cause
the service to misinterpret messages based on the old contract. For example, if a new parameter will
be added to an operation's signature, clients that use the old contract would send their messages
without that additional parameter; if the service is not designed to handle messages sent according to
the old contract these messages might fail to be processed.
Answer: Although a service can be designed to handle many concurrent requests, every service has
its limit. Even if you use the one-way message pattern, there is a limit to how many requests your
service can handle at a time. The only way to increase the throughput of your service (the number of
requests a service can handle at a given period of time), is by adding more instances of it, whether on
the same machine or by adding more machines.
Answer: Because services send their data over the network, the transmission can be listened to,
allowing attackers to capture the data and transmit false data. Therefore sensitive data must be
encrypted and signed so it cannot be deciphered or altered and authentication mechanisms need to
be used to prevent unauthorized access to sensitive services.
Service-Oriented Architecture 1-7
Additional Reading
SOA Has Built-in Security
• For more information about the web service security guidance from patterns & practices, see the
Improving Web Services Security: Scenarios and Implementation Guidance for WCF page on the
Microsoft website.
• For more information about the web application security guidance from OWASP, see Getting
Started page on the OWASP website.
1-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 3
Scenarios and Standards
Contents:
Question and Answers 9
Additional Reading 10
Service-Oriented Architecture 1-9
Answer: Intranet infrastructure allows the use of a faster network than the Internet network,
additional support for communication techniques, such as TCP, and the availability of advanced
authentication mechanisms such as Active Directory.
Answer: Interoperability means using standard protocols that various development technologies
understand, so services written in one technology can be consumed by other technologies. SOAP and
the WS-* standards were designed to support such interoperability.
1-10 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Services Use SOAP
For more information about the SOAP standard, see the Understanding SOAP page on the Microsoft
website.
It is a distributed world, business is getting more and more agile, and customers want more
but are willing to pay less.
2. What is a service?
A service is an entity that exposes functionality by receiving data and sometimes returning
data.
3. What are the main SOA principles?
Services are: autonomous, have explicit boundaries, share contract with their clients, deal
with data, not objects, and have interoperability through policy.
4. List the main benefits of SOA .
WS-* standards are specifications describing business and infrastructural data transfer
between services and clients.
6. What is REST?
Rest is an approach for development of interoperable services based on HTTP verbs and
URLs.
Tools
• Agility – services can be moved or changed without any effect on the rest of the system.
• Calling a service might be a long operation, so it must be clear that a network boundary is
crossed.
• A service call must be wrapped with error handling. It must be clear from reading the code that
you are calling a service.
• A service might be responsible for certain entities. Accessing these entities must be done using
explicit (and safe) calls to the service.
Module 2
Getting Started with Microsoft® Windows Communication
Foundation Development
Contents:
Lesson 1: Service Contract and Implementation 2
Lesson 2: Hosting WCF Services 4
Lesson 3: WCF Behaviors 7
Lesson 4: Consuming WCF Services 10
Module Reviews and Takeaways 17
Lab Review Questions and Answers 18
2-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
Service Contract and Implementation
Contents:
Question and Answers 3
Getting Started with Microsoft® Windows Communication Foundation Development 2-3
Answer: One of the SOA tenets is that services share contract and schema, but not types. This
approach enables true decoupling between different technologies and platforms. Service and
operation contracts are used to define the service as functionality where data contracts represent the
data model for interacting with the service.
2-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 2
Hosting WCF Services
Contents:
Question and Answers 5
Additional Reading 6
Getting Started with Microsoft® Windows Communication Foundation Development 2-5
Answer: The client needs to know the entire address, binding, and contract endpoint information—
the address so it can send the message to the correct place, the binding so it can send the message
using the required technology and specification, and the contract so it can send the message with the
correct operation name and data.
Message Pipeline
Question: Why do you need to be able to write your own custom binding elements?
Answer: If you want to check for something in each message that arrives to the service (for example
a special header that contains a user's security token), then you will prefer to write a binding element
and place it in the pipeline, so it will be called automatically on every message that arrives. This
prevents having to repeatedly call the same code in each operation of the service.
Answer: Without the predefined bindings, you would have to define a custom binding for each
endpoint you use, over and over again, in each service you build. Predefined bindings reflect the
common use of binding elements, such as the Basic HTTP binding that uses text encoded INSERT
Simple Object Access Protocol (SOAP ) over HTTP, which is a common way to construct a binding for
a service that is consumed over the Internet.
Answer: Self-hosting indicates that you apply the hosting within your process by yourself, and it is up
to you to explicitly create and open the service host.
2-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Responsibilities of a WCF Host
If you wish to use the same port in different endpoints, WCF offers solutions for port sharing for both TCP
and HTTP, required that the same transport is used in both endpoints. For more information about HTTP
and TCP port sharing and their limitations, see the Configuring HTTP and HTTPS, and the Net.TCP Port
Sharing page on the Microsoft website.
Message Pipeline
For more information about the order of binding elements in the pipeline, see the Custom Binding page
on the Microsoft website.
Binding Elements
For more information on how to build a custom transport element, see the Transport: UDP page on the
Microsoft website.
For more information about which encoder to use for your bindings, see the Choosing a Message Encoder
page on the Microsoft website.
For more information about using Fiddler, see the Fiddler PowerToy - Part 1: HTTP Debugging page on
the Microsoft website.
For more information about building a custom binding element, see the Creating a BindingElement page
on the Microsoft website.
For more information about selecting the right transports for your service, see the Choosing a Transport
page on the Microsoft website.
Defining an Endpoint
For more information about endpoint address naming, see the Specifying an Endpoint Address page on
the Microsoft website.
For more information about the service configuration editor, see the Configuration Editor Tool
(SvcConfigEditor.exe) page on the Microsoft website.
Getting Started with Microsoft® Windows Communication Foundation Development 2-7
Lesson 3
WCF Behaviors
Contents:
Question and Answers 8
Additional Reading 9
2-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: Behaviors can be applied both in development and post-development stages. There might
be deployment related behaviors which you will have to attach depending on the environment in
which the service is hosted. These behaviors can be set through configuration when the environment
is known.
Getting Started with Microsoft® Windows Communication Foundation Development 2-9
Additional Reading
Dispatchers and the Channel Stack
For more information about writing custom dispatchers, see the Extending Dispatchers page on the
Microsoft website.
Lesson 4
Consuming WCF Services
Contents:
Question and Answers 11
Detailed Demo Steps 12
Additional Reading 16
Getting Started with Microsoft® Windows Communication Foundation Development 2-11
Answer: The proxy pattern simplifies access between more complex objects and communication
patterns.
Answer: Once the service is available, the first step is to import the service metadata in order to
create the information required for communicating with the service. The Add Service Reference or
Svcutil command-line tool that comes with Visual Studio are common ways for importing service
metadata. Once the service is available, the first step is to import the service metadata in order to
create the information required for communicating with the service. The Add Service Reference or
Svcutil command-line tool that comes with Visual Studio are common ways for importing service
metadata.
Answer: The channel factory is used for creating communication channels to communicate with a
certain service contract. You can use the channel factory in cases where you don’t have the option or
need of generating automated proxy code and configuration.
2-12 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
• Log on to the virtual machine named 10263A-SVR1 as Administrator with the password
Pa$$w0rd.
• Open Visual Studio 2010 and select File, then select New, then selectProject, then select the
WCF Service Library, andthen click OK (if you don't see the project type, select WCF from the
Installed Templates for Microsoft Visual C#® or from Other Lanaguages and thenVisual
Basic, for Microsoft Visual Basic®).
• Verify that the WCF test client application is running and that you can see the service's
operations.
Note: Running the service library will open the WcfSvcHost.exe utility which automatically
hosts services with a configuration file. If you want to disable this option, you can do so in
the project settings, under WCF Options.
• In the Solution Explorer, right-click the console application and then select AddService
Reference.
• In the Add Service Reference window, click the Discover button. The service information will
appear.
• In the Solution Explorer, browse to the console application project and in eitherProgram.cs or
Module1.vb, enter the following code inside the Main method:
[Visual C#]
Console.WriteLine(str);
Console.ReadLine();
proxy.Close();
[Visual Basic]
Console.WriteLine(str)
Console.ReadLine()
proxy.Close()
• In the Solution Explorer, right click the console application project and then selectSet as Startup
Project.
5. Build the solution, and then run the client by pressing the F5 key. The client will call the service and
display the returned value.
• Log on to the virtual machine named 10263A-SVR1 as Administrator with the password
Pa$$w0rd.
• Open Visual Studio 2010 and select File, then select New, then selectProject, then select the
WCF Service Library, set the name of the project to TestService,andthen click OK (if you don't
see the project type, select WCF from the Installed Templates for Microsoft Visual C#® or from
Other Lanaguages and thenVisual Basic, for Microsoft Visual Basic®).
• Verify that the WCF Test Client application is running, and that you can see the service's
operations.
• Return to Visual Studio 2010 and select File, then select Add, then select New Project, then
select the Console Application project type under Visual C# or Other Lanaguages and then
Visual Basic, and then click OK.
• In the Solution Explorer, right-click the console application, and then select Add Reference.
• In the Add Reference dialog, move to the Projects tab, select the service project, and then click
OK.
• In the Solution Explorer, right-click the console application and select Add Reference.
• In the Add Referencedialog box move to the .NET tab, select both the System.ServiceModel
assembly and the System.Runtime.Serialization assembly, and then click OK.
• In the Solution Explorer, find the console application project and open the file named either
Program.cs or Module1.vb.
• Add the System.ServiceModel namespace to the “using” section of the Visual C# file, or the
"Imports" section for the Visual Basic file.
[Visual C#]
TestService.IService1 proxy =
ChannelFactory<TestService.IService1>.CreateChannel(
new BasicHttpBinding(),
new EndpointAddress("http://localhost:8080/testService"));
Console.WriteLine(str);
(proxy as ICommunicationObject).Close();
Console.ReadLine();
[Visual Basic]
ChannelFactory(Of TestService.IService1).CreateChannel(
New BasicHttpBinding(),
New EndpointAddress("http://localhost:8080/testService"))
Console.WriteLine(str)
TryCast(proxy, ICommunicationObject).Close()
Console.ReadLine()
• In the Solution Explorer, right click the console application project and then selectSet as Startup
Project.
6. Build the solution, and then run the client by pressing the F5 key. The client will call the service and
display the returned value.
2-16 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Adding a Service Reference
For more information about the "Add Service Reference" dialog, see the Add Service Reference Dialog Box
page on the Microsoft website.
A host brings a service to life. It creates endpoints, and listen for requests. When a request arrives, the
host sends it to an instance of the service to compute the response.
3. What is a binding?
A binding encapsulates all the technology concerned with sending a message from one point to
another. A binding is a combination of binding elements that together define the channel pipeline
through which messages travel.
4. What is a behavior?
A behavior is made up of component that controls various runtime aspects by controlling the
messaging dispatchers.
5. What is a proxy?
A proxy represents the service on the client side to allow simple access to the service.
A proxy reflects the service over the networking and messaging technological boundaries.
Best Practices
• Follow the contract first service development life cycle.
• Use behaviors to fine tune message handling and basic service properties.
• Create a client.
2-18 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
You start by creating the service's contract, then implementing the contract, then hosting the service
with a service host, then you test the service, and then you consume the service with a client
application.
The ServiceHost class is used for the creation of the service host
Endpoints can be defined in either the service configuration file, or in code when creating a
ServiceHost instance.
• Add Service Reference in Visual Studio 2010. This method is simple, but requires a lot of code and
configuration generation.
• ChannelFactory<T>. This method is clean, but requires some coding and referencing of the
contracts assembly.
Hosting Microsoft® Windows Communication Foundation Services 3-1
Module 3
Hosting Microsoft® Windows Communication Foundation
Services
Contents:
Lesson 1: WCF Service Hosts 2
Lesson 2: ServiceHost 4
Lesson 3: Hosting WCF Services in Windows Services 7
Lesson 4: IIS, WAS, and AppFabric 9
Lesson 5: Configuring WCF Hosts 12
Lesson 6: Service Hosting Best Practices 15
Module Reviews and Takeaways 17
Lab Review Questions and Answers 18
3-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
WCF Service Hosts
Contents:
Question and Answers 3
Hosting Microsoft® Windows Communication Foundation Services 3-3
Answer: The purpose of the host is to materialize the service and bring it to life. It is responsible for
managing the service lifetime and its resources.
3-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 2
ServiceHost
Contents:
Question and Answers 5
Additional Reading 6
Hosting Microsoft® Windows Communication Foundation Services 3-5
Answer: If the host does not open correctly, the service will be unavailable, and you will need to start
looking for the origin of the problem. Handling exceptions in the host creation sequence enables you
to log these errors, and makes it easier to locate the problem later if you discover that the service is
unavailable.
Answer: Each message contains information about the required operation, including the name of the
service contract to which that operation belongs. The dispatcher reads the content of the message
and recognizes to which contract the message refers.
3-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
The System.ServiceModel.ServiceHost Class
For more information about the ServiceHostBase class, see the ServiceHostBase Class page on the
Microsoft website.
For more information about extensible objects in WCF, see the Extensible Objects page on the Microsoft
website.
Lesson 3
Hosting WCF Services in Windows Services
Contents:
Additional Reading 8
3-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Using WCF Hosts in Windows Services
For more information about using a Windows Service to host your WCF service, see the How to: Host a
WCF Service in a Managed Windows Service page on the Microsoft website.
Hosting Microsoft® Windows Communication Foundation Services 3-9
Lesson 4
IIS, WAS, and AppFabric
Contents:
Question and Answers 10
Additional Reading 11
3-10 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: Using WAS offers you the benefit of IIS's health monitoring and management, which a
Windows Service does not.
Hosting Microsoft® Windows Communication Foundation Services 3-11
Additional Reading
Introduction to IIS and WAS
For more information about the IIS architecture, see the Introduction to IIS 7 Architecture page on the
Microsoft website.
For more information about hosting a WCF service under WAS, see the How to: Host a WCF Service in
WAS page on the Microsoft website.
Introduction to AppFabric
For more information about creating IIS deployment packages, see the Import and Export an Application
in Windows Server AppFabric page on the Microsoft website.
For more information about configuring deployment packages in IIS, see the Web Deploy page on the
Microsoft website.
Lesson 5
Configuring WCF Hosts
Contents:
Question and Answers 13
Additional Reading 14
Hosting Microsoft® Windows Communication Foundation Services 3-13
Answer: When you work in a development environment, you usually use a certificate that is issued to
your computer by your domain controller, or you use a self-issued certificate. When you move your
service to a production environment, your service needs to use a certificate that is issued by a trusted
CA. Therefore, you will need to change the configuration of the service so the host will look for a
different certificate.
3-14 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Configuring Service Diagnostics
For more information about enabling ETW tracing for your WCF service, see the ETW Tracing page on the
Microsoft website.
For more information about enabling a WMI provider for your WCF service, see the Using Windows
Management Instrumentation for Diagnostics page on the Microsoft website.
For more information about configuring WCF tracing for your services, see the Configuring Tracing page
on the Microsoft website.
Lesson 6
Service Hosting Best Practices
Contents:
Additional Reading 16
3-16 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Recommendations for Hosting WCF Services
For more information about hosting considerations, see the Internet Information Services Hosting Best
Practices page on the Microsoft website.
• Resource management.
• Configuration management.
• Monitoring.
• Error handling.
Host factories are code that isattached to an IIS and WAS host, and that is used to configure the host
exactly as required, or to provide a whole new custom host derived from the ServiceHost type.
Host the service using IIS, WAS, and AppFabric. IIS and WAS will allow you to host the WCF service
using both HTTP and TCP endpoints (without WAS you can only use HTTP). AppFabric will allow you
to monitor your service and collect information about its errors, including which operations caused
them.
2. You want to deploy your service in several locations to increase its availability to clients, so even if one
service shuts down, other services can take its place. How will you do this?
If the servers are in a web farm, make your clients use the address of the web farm to access the
service; the web farm itself will route the request to an available service. If you do not have a web
farm, create a WCF Routing Service that all clients will use, and set the routing service to direct the
calls to one of the available servers.
Best Practices
Mention some best practices in the context of your own business situations.
• Prefer placing service configuration in the host's configuration file rather than hard-coding it into the
host's creation code. You can also place the service configuration in the database, to create a central
configuration location for all the machines that hosts your service.
• Host WCF services under IIS 7.0 and AppFabric. If you cannot install IIS on the server, host your WCF
services using a WindowsService.
3-18 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
• Separate the service implementation from the hosting code. This way, if your service is currently
hosted using a WindowsService, it will be easy in the future to host it under IIS without changing too
much code.
Hosting Microsoft® Windows Communication Foundation Services 3-19
• In cases where Windows Server 2008 is not available, there is no alternative but to build a custom
host. The best candidate to run the host is a Windows Service.
• If the host requires user interaction, you can build a custom host inside any Windows application
(a common example is a smart client that needs to listen for notifications).
• Message logging
• Tracing
Defining and Implementing Microsoft® Windows Communication Foundation Contracts 4-1
Module 4
Defining and Implementing Microsoft® Windows
Communication Foundation Contracts
Contents:
Lesson 1: What Is a Contract? 2
Lesson 2: Contract Types 4
Lesson 3: Messaging Patterns 7
Lesson 4: Designing WCF Contracts 9
Module Reviews and Takeaways 12
Lab Review Questions and Answers 13
4-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
What Is a Contract?
Contents:
Question and Answers 3
Defining and Implementing Microsoft® Windows Communication Foundation Contracts 4-3
Answer: Without a contract, clients that want to consume the service will notknow which operations
are available to them, and whatdata those operations require and return.
Answer: To establish cooperation,the client and the server must define an agreement about the data
to be sent.
• Data representation (how the data should be formatted so the service will be able to
understand it correctly).
• Messaging patterns (how data should be sent, and how the result is retrieved).
• Error types (what kind of errors are expected from the service).
Answer: The service—like any other software module—has assumptions. The service knows what it
assumes, and can declare the type and shape of error information it will return, if and when these
assumptions are not met.
4-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 2
Contract Types
Contents:
Question and Answers 5
Additional Reading 6
Defining and Implementing Microsoft® Windows Communication Foundation Contracts 4-5
Answer: With a data contract, you can define what will be serialized, but not how it will be serialized
into the SOAP message. If you need to define where the data will be placed inside the message—
header or body—you will need to use a message contract.
Answer: Exceptions are objects, whereasservices exchange data. Some frameworks do not use
exceptions (for example,Component Object Module (COM)), so exceptions would create an unwanted
technological coupling. Fault contracts map exceptions to a data model.
4-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Defining Service Contracts
For more information about the Web Service Description Language (WSDL) definition and structure, see
the Understanding WSDL page on the Microsoft website.
For more information about using the XmlSerializerFormat attribute, see the Using the XmlSerializer Class
page on the Microsoft website.
For more information about serializable types, using the DataContractAttribute and SerializableAttribute,
see the Types Supported by the Data Contract Serializer page on the Microsoft website.
Lesson 3
Messaging Patterns
Contents:
Question and Answers 8
4-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: When a client calls a long-running service operation that uses the request-response message
pattern, the client needs to wait until the service responds to the request. Because services and clients
have a timeout for service operations, there might be situations where either the client or the service
will time out a long-running request and return a timeout fault. If a service performs a long-running
operation, it is advisable to use the one-way message patterns, and possibly an asynchronous service
operation. (Asynchronous service operations will be discussed in Module 8, "Introduction to Advanced
Microsoft® Windows Communication Foundation Topics".)
Answer: The callback pattern is a design pattern where a callback function is executed after some
function completes its work. This enables the caller to receive the response at another location, and
not at the call site.
Answer: By specifying the type of the callback contract, the client will know how it needs to create its
listener. Without specifying the callback contract, clients will not know what kind of messages to
expect from the service.
Defining and Implementing Microsoft® Windows Communication Foundation Contracts 4-9
Lesson 4
Designing WCF Contracts
Contents:
Question and Answers 10
Additional Reading 11
4-10 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: When you build your base class, you usually are not aware of all the derived classes that you
might add later. Sometimes derived classes are added after the service has been deployed through
the use of dependency injection. The need to send the list of derived types to the serializer in advance
is a problematic design which requires a better solution than using the KnownType attribute.
Answer: You should communicate the contract to the client by using contract-only assembly (code,
C# interfaces), or WSDL (XML).
Defining and Implementing Microsoft® Windows Communication Foundation Contracts 4-11
Additional Reading
Using the KnownType Attribute
For more information about building a data contract resolver, see the Using a Data Contract Resolver
page on the Microsoft website.
For more information about using the Known Types, see the Data Contract Known Types page on the
Microsoft website.
For more information about data contract versioning, see the Data Contract Versioning page on the
Microsoft website.
4-12 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
• Request-Response. The client sends a request, and the server responds synchronously with a
response.
• One-Way. The client sends a message, and continues working. The client might receive an answer
sometime in the future on another channel.
• Duplex Channel. The duplex channel is simulation of the callback pattern in the distributed world.
The client calls the service with information about the operation to be called on the client-side
when the service operation concludes. The service creates a proxy back to the client and calls a
callback method on the client. A duplex channel combines a channel from the client to the
service, with a channel from the service to the client.
WSDL is an XML standard to describe service. The WSDL document describes the messages to be sent
to the service, and the messages returned to the client. The WSDL describes the service and the
contract. The client can use the WSDL to reflect the interfaces and the classes necessary to create a
proxy and call the service.
The KnownType attribute is used on base types to specify which derive types the Data Contract
Serializer can expect when serializing and deserializing types.
Set the service's operation to receive a message contract instead of a data contract, and build the
message contract so that the fields that need to be placed in the message's header will be decorated
with the MessageHeader attribute.
2. You need to build a service operation for a graphical system that returns a Shape type object, which
can be a Circle type, a Rectangle type, a Polygon type, or an Ellipse type. How will you define the
data contracts so a client will be able to receive these objects?
Decorate the Shape type with the KnownType attribute for each of the derived types. This way, the
WSDL documentation of the service will include the data contract of all derived types, allowing the
client to deserialize them when they are returned from the service's operation.
3. You need to build a service that notifies clients of changes in stock quotes. Which message pattern is
most suitable for this service?
Use the Duplex message pattern. You can construct a service that exposes a RegisterToQuote
operation that allows a client to register notifications for a specific stock. The service will also expose a
client callback contract that has a NotifyStockChange operation that the client will implement
accordingly, and which the service will call whenever it detects a change on the required stock.
Defining and Implementing Microsoft® Windows Communication Foundation Contracts 4-13
You create an interface and decorate it with the ServiceContract and OperationContract attributes.
You add the serviceMetadata behavior with httpGetEnabled attribute set to true in the service
behavior configuration.
Endpoints and Behaviors 5-1
Module 5
Endpoints and Behaviors
Contents:
Lesson 1: Multiple Endpoints and Interoperability 2
Lesson 2: WCF Discovery 11
Lesson 3: WCF Default Endpoints 14
Lesson 4: Instancing and Concurrency 17
Lesson 5: Reliability 20
Module Reviews and Takeaways 26
Lab Review Questions and Answers 28
5-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
Multiple Endpoints and Interoperability
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 9
Endpoints and Behaviors 5-3
Answer: Interoperability is when technology A can consume technology B, and vice versa.
5-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
• Click Start, click All Programs, click Microsoft Visual Studio 2010, and then click Microsoft
Visual Studio 2010.
• In the Solution Explorer window, right-click the AsmxCalc.asmx file, and then select View in
Browser.
6. Test the ASMX Web Service using the ASMX testing page. Test the Add operation with the values a:
5, b: 3.
• Click either Visual C# or click Other Languagesand then click Visual Basic, and then select the
Console Application project type.
• Set the name of the project to CalculatorsClient, and then click OK.
9. In the client console application, add a Service Reference to the ASMX Web Service, using the
automatic discovery option in the Add Service Reference dialog box. Set the namespace of the
service reference to AsmxCalcServiceReference.
• In the Solution Explorer window, right-click the console application, and then select Add
Service Reference.
• In the Add Service Reference dialog box, click the Discover button. The services information
appears.
Endpoints and Behaviors 5-5
• Select the AsmxCalc.asmx from the Services list, change the target namespace to
AsmxCalcServiceReference, and then click OK.
10. In the client console application, in the Add Service Reference window, in the Add Web Reference
dialog box, use the automatic discovery option to add a Web Reference to the WCF Service. Set the
namespace of the web reference to WcfCalcServiceReference.
• In the Solution Explorer window, right-click the console application, and then select Add
Service Reference.
• In the Add Service Reference window, click the Advanced button and in the Service Reference
Settings dialog box, and then click the Add Web Reference button.
• In the Add Web Reference dialog box, click the Web services in this solution link, and then
click the WcfCalc service.
• Change the web reference name to WcfCalcServiceReference, and then click Add Reference.
• In the Solution Explorer window, find the console application and open either Program.cs or
Module1.vb.
[Visual C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CalculatorsClient.AsmxCalcServiceReference;
using CalculatorsClient.WcfCalcServiceReference;
namespace CalculatorsClient
class Program
int result;
value1 = rnd.Next(100);
value2 = rnd.Next(100);
Console.WriteLine(
asmxClient.Close();
bool resultSpecified;
value1 = rnd.Next(100);
value2 = rnd.Next(100);
wcfClient.Mul(
value1 = rnd.Next(100);
value2 = rnd.Next(100);
wcfClient.Div(
Console.WriteLine();
Console.ReadLine();
}
Endpoints and Behaviors 5-7
[Visual Basic]
Imports System.Text
Imports CalculatorsClient.AsmxCalcServiceReference
Imports CalculatorsClient.WcfCalcServiceReference
Module Module1
value1 = rnd.Next(100)
value2 = rnd.Next(100)
result)
asmxClient.Close()
value1 = rnd.Next(100)
value2 = rnd.Next(100)
resultSpecified)
5-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
value1 = rnd.Next(100)
value2 = rnd.Next(100)
resultSpecified)
Console.WriteLine()
Console.ReadLine()
End Sub
End Module
• In the Solution Explorer window, Right-click the CalculatorsClient project, and then select Set
as Startup Project.
15. Examine the output of the console application. The output should resemble the following output
(values in operations are random):
Add(41,34)=75
Subtract(13,34)=-21
Mul(77,38)=2926
Div(77,5)=15
Note: The WCF contract that is exposed by the Web Services Description Language (WSDL)
document marks the parameters of the operation as not required, meaning it can receive
null values. WCF clients can overcome this WSDL setting, but non-WCF clients might
translate this to a requirement of an additional isSpecified parameter to support the
use of nullable values.
Endpoints and Behaviors 5-9
Additional Reading
Introduction to Interoperability
For more information about the protocols used by various bindings, see the Web Services Protocols
Supported by System-Provided Interoperability Bindings page on the Microsoft website.
For an example of consuming WCF services using a non-WCF client, see the How to: Configure WCF
Service to Interoperate with ASP.NET Web Service Clients page on the Microsoft website.
Introduction to REST
For more information about REST and WCF, see the Overview of REST in WCF page on the Microsoft
website.
For more information about building a WCF service that supports REST, see the REST and POX page on
the Microsoft website.
For more information about WCF Data Services, see the WCF Data Services page on the Microsoft website.
[Visual C#]
[ServiceContract]
[OperationContract]
[WebGet(UriTemplate="Add?a={a}&b={b}")]
[OperationContract]
[WebGet(UriTemplate = "Sub?a={a}&b={b}")]
[OperationContract]
[WebGet(UriTemplate = "Mul?a={a}&b={b}")]
[OperationContract]
5-10 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
[WebGet(UriTemplate = "Divide?a={a}&b={b}")]
[Visual Basic]
<ServiceContract>
<OperationContract, WebGet(UriTemplate:="Add?a={a}&b={b}")>
End Interface
For example, in order to call the Mul operation with a=4 and b=5, you will need to send an HTTP request
to the address http://localhost:5015/Restful/Mul?a=4&b=5.
Endpoints and Behaviors 5-11
Lesson 2
WCF Discovery
Contents:
Question and Answers 12
Additional Reading 13
5-12 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: No. discovery announcements and Probe/Resolve messages uses the UDP transport, which
cannot be used outside the local subnet boundary. To use discovery outside the subnet—for example
on the Internet—use a discovery proxy.
Endpoints and Behaviors 5-13
Additional Reading
The Process of Ad-Hoc Discovery
For more information about Ad-Hoc Discovery and WS-Discovery, see the Web Services Dynamic
Discovery (WS-Discovery) Version 1.1 page on the OASIS website.
Lesson 3
WCF Default Endpoints
Contents:
Question and Answers 15
Additional Reading 16
Endpoints and Behaviors 5-15
Answer: Using .NET Reflection, the host checks each of the service's interfaces for the
ServiceContract attribute. The host then creates an endpoint for each contract it finds, settings its
address to the host's base address, and setting its binding to the binding that is mapped to the
address's scheme.
5-16 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Introduction to Default Endpoints
For more information about default endpoints, see the Simplified Configuration page on the Microsoft
website.
Endpoints and Behaviors 5-17
Lesson 4
Instancing and Concurrency
Contents:
Question and Answers 18
Additional Reading 19
5-18 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: The service code is executed by an instance of the service implementation class.
Question: Who creates the service implementation class instance, and when?
Answer: The dispatcher runtime is responsible for service instancing. The instance context mode
controls instancing.
Answer: When the instancing mode is set to PerCall, each request will receive its own instance of the
service. If a reentrant call is made, it will be handled by a new service instance and will not be blocked
because the instance will only be used by a single thread, eliminating the possibility of a deadlock.
Endpoints and Behaviors 5-19
Additional Reading
Introduction to Instance Context Modes
For more information about setting the instancing mode and the session mode, see the SessionMode
Enumeration page on the Microsoft website.
Lesson 5
Reliability
Contents:
Question and Answers 21
Detailed Demo Steps 22
Additional Reading 25
Endpoints and Behaviors 5-21
Answer: No, the Basic HTTP Binding does not support reliable messaging. This binding does not
support any WS-* standard, including WS-ReliableMessaging.
5-22 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
• Click Start, click All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual
Studio 2010.
3. Open the solution MSMQ.sln from either the D:\Demofiles\M05\MSMQ\CS folder or the
D:\Demofiles\M05\MSMQ\VB folder.
• In the File menu, select Open, and then click Project/Solution.
• In the Open Project dialog box, browseto either the D:\Demofiles\M05\MSMQ\CS folder or
the D:\Demofiles\M05\MSMQ\VBfolder, click the MSMQ.sln file, and then click Open.
Note: Each of the operations in the service contract is marked as a one-way operation, because when you
use MSMQ, your service operations cannot return a value, and therefore WCF forces you to mark them as
one-way.
Note: class—which belongs to the System.Messaging namespace—allows you to check for the existence of
an MSMQ queue, and create it if it does not already exist.
• In the Solution Explorer window, right-click the CalcService project, and then select Set as
Startup Project.
Note: The first execution of the service will create the queue necessary for the client to communicate with
the service.
• In the Solution Explorer window, right-click the Client project, and then select Set as Startup
Project.
• Make sure the service is not running —the console window of the service host should be closed.
8. Examine the output of the console application. The output should resemble the following output—
values in operations are random):
Add(48,27)
Subtract(3,69)
Multiply(25,65)
Divide(41,66)
The client does not fail even though the service is not running. The messages sent from the client will be
stored in the service's queue until the service is opened.
10. amine the content of the calculator queue—you should see four messages inside the queue.
• Return to Visual Studio 2010, select View, and then selectServer Explorer.
• In the Server Explorer window, select Servers, then select10263A-SVR1, then selectMessage
Queues, then selectPrivate Queues, then selectcalculator, and then select Queue messages.
Note: You can see the message's information by right-clicking a message, and then selecting Properties.
From the Properties window, you can also see the content of the message—which is binary encoded,by
selecting the BodyStream property, and then clicking the ellipses (…) button.
11. Run the service host, and observe as the messages disappear from the queue.
• In the Solution Explorer window, right-click the CalcService project, and then select Set as
Startup Project.
12. Examine the output of the service host. The output should resemble the following output—values in
operations are random:
14. Examine the content of the calculator queue—you should see no messages inside the queue.
• Return to Visual Studio 2010, select View, and then selectServer Explorer.
• In the Server Explorer window, select Servers, then select10263A-SVR1, then selectMessage
Queues, then selectPrivate Queues, then selectcalculator, and then select Queue messages.
5-24 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Note: If you returned to the Visual Studio 2010 instance where the queue's content is already shown, refresh
it by right-clicking the calculator queue, and then selecting Refresh.
Endpoints and Behaviors 5-25
Additional Reading
Introduction to Reliable Messaging
For more information about WS-ReliableMessaging, see the Reliable Messaging Protocol version 1.1 page
on the Microsoft website.
For more information about best practices using reliable messages, see the Best Practices for Reliable
Session page on the Microsoft website.
For more information about exposing and consuming queued services, see the How to: Exchange Queued
Messages with WCF Endpoints page on the Microsoft website.
For more information about queue addresses, see the Service Endpoints and Queue Addressing page on
the Microsoft website.
Interoperability is the ability of multiple technologies to cooperate so one can consume the other.
2. What is REST?
• REST is an architectural style. Its main purpose is interoperability and loose coupling between
systems.
3. What are the differences between Ad-Hoc Discovery and a Discovery Proxy?
Setting the concurrency to single might cause a deadlock when a service calls another service or
sends a callback.
For the Internet client, you can use the WS-HTTP binding, or even the Basic HTTP binding, if you do
not have any special security or reliability requirements. For the intranet clients, you should use the
TCP binding, which has better performance and smaller message sizes than the various HTTP
bindings.
2. You do not have a web farm in your organization, but you need to deploy your service on several
servers to support increasing number of requests. How can you achieve this?
Use Ad-Hoc discovery with probe messages to allow your client to locate the different instances of
your service across the network. Your services will expose the udpDiscoveryEndpoint type, and your
clients can use the DynamicEndpoint type to consume the services, wherever they might reside on
the network.
Endpoints and Behaviors 5-27
3. Your service is using the one-way message pattern for its operations, and it is expected that in the
future, it will need to handle a high load of requests. What can you do to increase your service
throughput?
Although you can invest in buying more machines to host more instances of the service, you should
first try to use MSMQ to queue up the messages received by your service. Using MSMQ will allow you
to handle larger loads of requests without getting timeouts from your service and having to invest in
purchasing many more servers.
Best Practices
Mention some best practices in the context of your own business situations.
• Use one way services with MSMQ for reliable and scalable services.
• Use transactions with care. Transaction simplifies error handling, but they come with a cost.
The service contract is divided into several groups of operation. The service can implement multiple
contracts.
You can define multiple endpoints for the service using the required contract and binding.
MSMQ communication can use the NetMSMQ Binding and MSMQ-Integration Binding.
3. What are the steps required to make a service run within a transaction?
Add a discovery endpoint to accept discovery messages, or add a discovery behavior to send
announcement messages.Which behavior is responsible for instancing and concurrency?
The ServiceBehavior has the ConcurrencyMode property to specify the concurrency mode, and the
InstanceContextMode property to specify the instance context mode.
5. What happens when a message is sent over MSMQ but the target service is unavailable?
The message is kept in the queue. When the service becomes available, it will read it from the queue.
This is how queues mask service unavailability from the clients.
Testing and Troubleshooting Microsoft® Windows Communication Foundation Services 6-1
Module 6
Testing and Troubleshooting Microsoft® Windows
Communication Foundation Services
Contents:
Lesson 1: Errors and Symptoms 2
Lesson 2: WCF Faults 4
Lesson 3: Debugging and Diagnostics Tools 7
Lesson 4: Runtime Governance 12
Module Reviews and Takeaways 15
Lab Review Questions and Answers 17
6-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
Errors and Symptoms
Contents:
Question and Answers 3
Testing and Troubleshooting Microsoft® Windows Communication Foundation Services 6-3
Answer: A service that does not support multiple clients will be able to support only one concurrent
client at a time. If the service is called by numerous clients, each client will need to wait for the
previous client to complete its process, and eventually this can cause clients to time out and fail.
6-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 2
WCF Faults
Contents:
Question and Answers 5
Additional Reading 6
Testing and Troubleshooting Microsoft® Windows Communication Foundation Services 6-5
Answer: A service should be interoperable, meaning you can use various technologies to call the
service. Therefore, WCF services use the SOAP standard for messages, whether it is for requests,
responses, or faults.
Answer: You need to declare your error information data types as data contracts, so their structure
will be included in the WSDL document.
6-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Introducing Fault Message
For more information about SOAP faults, see the SOAP Version 1.2 page on the W3C website.
Lesson 3
Debugging and Diagnostics Tools
Contents:
Question and Answers 8
Detailed Demo Steps 9
Additional Reading 11
6-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: The overhead of logging each action can harm your service's performance, and can lead to
your server running out of disk space.
Testing and Troubleshooting Microsoft® Windows Communication Foundation Services 6-9
• Click Start, click All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.
3. Open the solution Calculator.sln from either the D:\Demofiles\M06\Calculator\CS folder for
Microsoft Visual C#® or from the D:\Demofiles\M06\Calculator\VB folder for Microsoft Visual
Basic®.
5. Open the Calculator project's App.config file in the WCF Service Configuration Editor.
• In the Solution Explorer window, right-click the App.config file, and then select Edit WCF
Configuration.
6. Ensure that MessageLogging and Tracing is turned on.
• Return to Visual Studio 2010. If a reload confirmation message appears when returning to
Visual Studio 2010, click Yes.
10. Verify that the WCF Test Client application is running, and that you can see the service's operations.
11. Test the Divide operation with the values of a=10, b=5.
• Double-click the Divide operation, and set the values of the request to a=10, b=5.
• Click Invoke, and if a security warning appears, click OK.
6-10 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
12. Test the Divide operation with the values of a=10, b=0.
• Double-click the Divide operation, and set the values of the request to a=10, b=0.
13. Examine the error message, and then close the error window by clicking Close.
15. Open the Calculator project's tracing file with the Service Trace Viewer.
• Return to Visual Studio 2010, right-click the Calculator project, and then select Open Folder
in Windows Explorer.
• Double-click the app_tracelog.svclog file. This opens the file with the Microsoft Service
Trace Viewer.
Note: If your service is still running when you are opening the trace file, you
might get an error message—this is because the file is currently opened by the
service, and is still in the writing process.
16. Select the faulty activity, and examine the content of the exception.
• In the Activity list, select the activity in red text.
Additional Reading
Using the WCF Test Client
If you wish to read more information about the WCF Test Client, see the WCF Test Client
(WcfTestClient.exe) page on the Microsoft website.
For more information about using the configuration editor, see the Configuration Editor Tool
(SvcConfigEditor.exe) page on the Microsoft website.
For more information about configuring message logging, see the Configuring Message Logging page on
the Microsoft website.
Lesson 4
Runtime Governance
Contents:
Question and Answers 13
Additional Reading 14
Testing and Troubleshooting Microsoft® Windows Communication Foundation Services 6-13
Answer: Increasing the number of concurrent calls allows the service to handle more requests at a
given time, which is suitable for situations when a service has a heavy load of requests reaching it.
However, you should test your service after changing this setting to make sure your service's memory
consumption has not increased too much, and that your CPU usage has not overloaded and reached
100 percent.
6-14 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Introduction to Runtime Governance
For more information about AppFabric, see the Windows Server AppFabric page on the Microsoft website.
A fault message is a data representation of an error. Faults are standardized in the SOAP
standard. When a service needs to return error information, it is put inside a fault message.
• Throughput
• Latency
• Message size
• Resource consumption
4. What tools does WCF provide to test runtime behavior?
Add Message logging and Tracing to the service's configuration, wait for an error to occur and
then use the SvcTraceViewer.exe to check the logs for any exception thrown by the service.
2. Your service is experiencing a high-load of requests, and some of the requests are thrown back to
the client because of a time out. What can you do?
Increase the throttling settings of the service to allow more requests to be handled at the same
time, and then use the Windows Performance Monitor to test the service to see if requests are no
longer timing out, and that the memory consumption and CPU usage are in acceptable ranges.
6-16 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Best Practices
Mention some best practices in the context of your own business situations.
• Increasing the limits set by WCF will not always make your service work faster, so be sure to test
your service after making changes to its configuration.
Testing and Troubleshooting Microsoft® Windows Communication Foundation Services 6-17
WCF catches all unhandled exceptions. If the exception is not a declared in a fault contract, WCF
will create a new empty fault message and send it back to the client. When a fault message
arrives at the client, WCF generates and throws a new empty FaultException.
Error handlers are an extensibility point in WCF fault handling. They convert exceptions to faults.
and can provide additional functionality—such as logging—in the error-handling process
You must enable message logging and tracing in the service’s configuration file. (You can use the
WCF Service Configuration Editor.)
Module 7
Security
Contents:
Lesson 1: Introduction to Application Security 2
Lesson 3: Transport and Message Security 4
Lesson 4: Authentication and Authorization 7
Lesson 5: Claim-Based Identity 10
Module Reviews and Takeaways 12
Lab Review Questions and Answers 14
7-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
Introduction to Application Security
Contents:
Additional Reading 3
Security 7-3
Additional Reading
Understanding Application Security Tenets
For more information about implementing security measures in your application, see the Improving Web
Services Security: Scenarios and Implementation Guidance for WCF page on the Microsoft website.
7-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 3
Transport and Message Security
Contents:
Question and Answers 5
Additional Reading 6
Security 7-5
Answer: Transport security requires that the service supply a certificate as part of the SSL handshake.
In the WS-DualHTTP binding, both the client and service operate as a service and open an HTTP
channel, implying that the client will also need to identify itself using a certificate. Since each client
will need to have a unique certificate, and the service needs to recognize the certificate, it would
create a complicated deployment scenario. Therefore, this binding does not support transport
security. Although transport security is not supported, other security measures exist that you can use
to protect your messages.
Answer: Message security encrypts the message in the WCF security channel, and not on the
transport layer, as with transport security. This allows the message to be encrypted on one side of the
service, and decrypted on the other side (end-to-end) without allowing intermediary servers to
decrypt the data. In addition, message security allows the use of more authentication types than
transport security, including custom authentication types. Message security also creates larger
messages than messages created with transport security.
Answer: The service certificate that is written in the client’s endpoint configuration can be used to
verify that the service responding to the client is the genuine service, and not a malicious
intermediary.
7-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Using Transport Security
For more information about transport security and SSL, see the HTTP Transport Security page on the
Microsoft website.
For more information about configuring certificates in IIS, see the Configuring Server Certificates in IIS 7
page on the Microsoft website.
For more information about using SSL for self-hosted services, see the How to: Configure a Port with an
SSL Certificate page on the Microsoft website.
For more information about setting the client's certificate, see the <clientCertificate> of
<serviceCredentials> page on the Microsoft website.
Lesson 4
Authentication and Authorization
Contents:
Question and Answers 8
Additional Reading 9
7-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: Roles add an additional level of distinction that allows you to declare policies and attach
policies to users, thus allowing you to control which users can access different parts of your service,
and what those users can do.
Security 7-9
Additional Reading
Using Custom Authentication Providers
For more information about creating a custom username and password validator, see the How to: Use a
Custom User Name and Password Validator page on the Microsoft website.
For more information about creating custom client and service credentials, see the Walkthrough: Creating
Custom Client and Service Credentials page on the Microsoft website.
Lesson 5
Claim-Based Identity
Contents:
Additional Reading 11
Security 7-11
Additional Reading
Using Tokens to Authenticate a Claim-Based Identity
For more information about security tokens and STS, see the Brokered Authentication: Security Token
Service (STS) page on the Microsoft website.
For more information about the WS-Federation HTTP Binding, see the How to: Create a
WSFederationHttpBinding page on the Microsoft website.
For more information about the Windows Identity Framework, see the Overview page on the Microsoft
website.
For more information about AD FS, see the Microsoft Active Directory Federation Services page on the
Microsoft website.
7-12 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
The tenets of application security are: Input Validation, Authentication, Authorization, Cryptography,
Sensitive Data, Session Management, Configuration, Management, Parameter Manipulation,
Exception Management,and Auditing and Logging.
• With transport security, the transport layer handles message encryption and integrity.
Transport security is simple and efficient.
• With message security, the WCF security channel is responsible for message encryption and
integrity. WCF enforces authentication and authorization. Message security is extensible.
4. What types of credentials does WCF support?
• Username-password
• X.509
• SAML
• Custom
Claim-based identity is an identity that isprovided as a set of claims that are grouped inside a token.
Security tokens are created by a special service (STS), which is separate from the application—the
application must trust the STS). The application uses the claims for authorization,and for its business
functionality.
Use a transport security with Windows credentials for authentication, and use role-based security and
the PrincipalPermission attribute for user authorization.
2. You need to expose a secured service on the Internet for unknown clients. Which security
configuration will you use?
For WCF clients and for clients that know how to use the WS-Security standards, you can use message
security with username authentication. For non-WCF clients that do not know how to use the WS-
Security standards, use transport security with username authentication. In both cases, you can use
the ASP.NET Membership provider to manage the user names and passwords. You can also use the
Security 7-13
ASP.NET Membership provider to manage user roles, which then allows you to use the
PrincipalPermission attribute to authorize users.
Best Practices
Mention some best practices in the context of your own business situations.
• Apply security concerns to your preliminary service design, to prevent security pitfalls later on in
the production.
• Use authentication types that are common to your organization, so you will be able to
interoperate with other systems in your organization without needing to supply them with
special authentication tokens.
• Use message and transport security with caution. They can both help to improve your service's
security, but they can also harm its performance—apply them only where necessary.
• If you need to provide an extensible claim set, consider using claim-based identities instead of
writing your own custom authentication and authorization provider.
7-14 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
2. Create a behavior for the token negotiation. Set the server credentials to a specific certificate that
is used to secure the channel.
4. Apply the binding and behavior to the service configuration and endpoints.
1. Configure the web server to listen on a secure port (SSL is port 443 by default). To do that,
configure a certificate for use, and attach it to the web application.
2. Create a binding configuration with securityMode=Transport.
3. Ensure that the address you use complies with the SSL addressing scheme (HTTPS).
• Windows and AD DS
5. What is a security negotiation?
A security negotiation is the process in which the client and the server exchange security messages
according to WS-* security standards. For example, before the establishment of a secure channel, the
client and server send messages to exchange a key that will be used for message encryption.
Introduction to Advanced Microsoft® Windows Communication Foundation Topics 8-1
Module 8
Introduction to Advanced Microsoft® Windows
Communication Foundation Topics
Contents:
Lesson 1: The Asynchronous Invocation Pattern 2
Lesson 2: Extending WCF 5
Lesson 3: Routing 8
Lesson 4: Workflow Services 11
Module Reviews and Takeaways 14
Lab Review Questions and Answers 15
8-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Lesson 1
The Asynchronous Invocation Pattern
Contents:
Question and Answers 3
Additional Reading 4
Introduction to Advanced Microsoft® Windows Communication Foundation Topics 8-3
Answer: Asynchronous client calls can improve the responsiveness of your client application, so it will
not hang when calling a service operation that takes a while to complete.
8-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
Implementing Asynchronous Clients
For more information about the asynchronous pattern, see the Synchronous and Asynchronous
Operations page on the Microsoft website.
For more information about asynchronous programming, see the Asynchronous Programming Design
Patterns page on the Microsoft website.
Introduction to Advanced Microsoft® Windows Communication Foundation Topics 8-5
Lesson 2
Extending WCF
Contents:
Question and Answers 6
Additional Reading 7
8-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: There may be occasions when you need to access the message itself to either extract
information from it or change it, before it is forwarded to your service implementation, or before
sending the response back to the client. For example, you might build a message inspector to handle
calls made by older client that are unaware to changes made to your service contract. The message
inspector will transform the old version structure to a new structure upon receiving the message, and
format the new version to the old version prior to returning a response.
Answer: Operation parameters are designed to hold information that is required for the operations
itself, whereas custom headers are used in cases when the service's infrastructure requires additional
information that is not included in the standard headers that are added by WCF to messages. For
example, if you build a custom security authentication header that is a part of your service
infrastructure, you would add it as a custom header instead of adding an additional userId parameter
to every one of your service's operations.
Introduction to Advanced Microsoft® Windows Communication Foundation Topics 8-7
Additional Reading
Responsibilities of WCF Dispatchers
For more information about the dispatchers, see the Extending Dispatchers page on the Microsoft
website.
Lesson 3
Routing
Contents:
Question and Answers 9
Additional Reading 10
Introduction to Advanced Microsoft® Windows Communication Foundation Topics 8-9
Answer: By using routing services, you can direct calls made to a failed service to another instance of
the service without the client being aware to the failover. This creates the illusion that the service is
always available.
8-10 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Additional Reading
The Benefits of Routing
For more information about routing purposes, see the Routing Overview page on the Microsoft website.
For more information about routing scenarios, see the Routing Scenarios page on the Microsoft website.
For more information about the contracts implemented by the routing service, see the Routing Contracts
page on the Microsoft website.
Lesson 4
Workflow Services
Contents:
Question and Answers 12
Additional Reading 13
8-12 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Answer: When a workflow instance is long running—which can take several hours or even days (for
example, a workflow has an approval activity that requires getting approval from several users)—best
practice is to persist the workflow instance. This frees the memory of the Workflow Service, and
increases the available resources for other workflow instances.
Introduction to Advanced Microsoft® Windows Communication Foundation Topics 8-13
Additional Reading
Introduction to Workflow Foundation
For more information about creating custom activities, see the How to: Create a Custom Activity Designer
page on the Microsoft website.
For more information about hosting the WF designer, see the Rehosting the Workflow Designer page on
the Microsoft website.
Custom headers should contain infrastructure information that is not part of the business
information. The separation between infrastructure and business information is done by
separating the information between the header part (infrastructure) and the body part (business)
of the message.
2. What are the advantages of Workflow Services for WCF services implementation?
• Workflow Services provides persistence and tracking, which is essential for any long-running
process.
Dispatchers are components thatare responsible for translating the content of the message to a
method invocation.
4. What is the scenario in which the asynchronous pattern on the server can improve the
service throughput?
When an operation performs a blocking call—for example when calling a database operation or
when calling another service—its thread cannot be used to handle other waiting requests. By
using the asynchronous pattern, you can release the thread for other requests until the blocked
call completes, thus increasing your service's throughput.
You attach message inspectors to the dispatch runtime of the endpoint dispatcher object. The
following steps are required to attach a custom message inspector:
• Provide extra functionality that is accessible to the instances that the host executes.
3. What are the steps that are required to implement the asynchronous pattern on the service-
side and on the client-side?
1. Create a contract with BeginXXX and EndXXX methods (where XXX is the operation name).
1. Use the Visual Studio 2010 Add Service Reference dialog box. In the advanced options
section, select the Generate Asynchronous Operations check box.
2. Configure the web server to listen on a secure port (SSL is port 443 by default). To do that,
configure a certificate for use, and attach it to the web application.
3. Create a binding configuration with securityMode="Transport".
• NET 4 routers establish one access point to a distributed system. The client calls the router, which
will then forward the message to the correct service. Services can change their location in a
manner that is transparent to the clients.
• NET 4 routers provides backup lists. If a service fails to accept a call, another service from the
backup list will be used, improving service reliability and masking unavailability.
5. What Workflow Foundation activities can you use to implement a Workflow Service?
Resources
Contents:
Microsoft Learning 2
Technet and MSDN Content 3
Communities 7
R-2 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Microsoft Learning
This section describes various Microsoft Learning programs and offerings.
• Microsoft Learning
MSDN content
This section includes content from MSDN for this course.
Module 1
• Service-Oriented Architecture
• The web service security guidance from patterns & practices
• The web application security guidance from OWASP
• The SOAP standard
• The WS-* standards
Module 2
• Which encoder to use for your bindings
• Using Fiddler
• Configuring HTTP and HTTPS
• HTTP and TCP port sharing and their limitations
• The order of binding elements in the pipeline
• How to build a custom transport element
• Building a custom binding element
• The Named Pipes protocol
• Selecting the right transports for your service
• Endpoint address naming
• The service configuration editor
• Writing custom dispatchers
• The ServiceBehavior attribute
• The "Add Service Reference" dialog
• How to use the Svcutil.exe to create proxies
Module 3
• The ServiceHostBase class
• Extensible objects in WCF+J13
• Setting an endpoint's address
• Using a Windows® Service to host your WCF service
• information about AppFabric’s distributed cache
• The IIS architecture
R-4 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Module 4
• The Web Service Description Language (WSDL) definition and structure
• Serializable types, using the DataContractAttribute and SerializableAttribute
• Using the XmlSerializerFormat attribute
• Including exception details in faults
• Data contract versioning
• Building a data contract resolver
• Using the Known Types
• Defining data contract names and namespaces
Module 5
• The protocols used by various bindings
• Consuming WCF services using a non-WCF client
• REST and WCF
• Building a WCF service that supports REST
• WCF Data Services
• Protocols interoperability
• Ad-Hoc Discovery and WS-Discovery
• Using the kind attribute in endpoints
• Ways to search services
• Discovery service implementation
• Default endpoints
• Setting the instancing mode and the session mode
• Maintaining state using the host's extensions
• Concurrency and instancing
Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010 R-5
• Distributed transaction
• WS-Coordination and WS-AtomicTransaction messages
• WS-ReliableMessaging
• Best practices using reliable messages
• How queues work
• Using queues in WCF
• Exposing and consuming queued services
• Queue addresses
• How transactions work
• The ReleaseServiceInstanceOnTransactionComplete property
• The TransactionScope class
Module 6
• SOAP faults
• The fault transmission differences between SOAP 1.1 and SOAP 1.2
• FaultException(Of TDetail) Class
• The different techniques to build new behaviors
• Debugging and Diagnostics Tools
• The WCF Test Client
• Configuring tracing in code
• The configuration editor
• Configuring message logging
• The WCF Trace Viewer
• AppFabric
• WCF performance counters
• AppFabric and related technologies
• Service throttling
Module 7
• Implementing security measures in your application
• Transport security and SSL
• Credential types
• Configuring certificates in IIS
• Using SSL for self-hosted services
• Message security
• SAML
R-6 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Module 8
• Extending Dispatchers
• Asynchronous Programming Design Patterns
• The asynchronous pattern
• Implementing an asynchronous service operation
• The dispatchers
• The client runtime
• Other runtime components
• Message inspectors
• Behavior types
• Extending runtime classes
• Routing purposes
• Routing scenarios
• The routing service
• The contracts implemented by the routing service
• Message filters
• The routing service features and behaviors
• Creating custom activities
• Hosting the WF designer
• Workflow variables
• WF developing
Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010 R-7
Communities
Microsoft Technical Communities Web site.
R-8 Developing Microsoft® Windows Communication Foundation Solutions with Microsoft Visual Studio® 2010
Note Not all training products will have a Knowledge Base article – if that is the case, please ask your
instructor whether or not there are existing error log entries.
Courseware Feedback
Send all courseware feedback to support@mscourseware.com. We truly appreciate your time and effort.
We review every e-mail received and forward the information on to the appropriate team. Unfortunately,
because of volume, we are unable to provide a response but we may use your feedback to improve your
future experience with Microsoft Learning products.
Reporting Errors
When providing feedback, include the training product name and number in the subject line of your e-
mail. When you provide comments or report bugs, please include the following:
Please provide any details that are necessary to help us verify the issue.
Important All errors and suggestions are evaluated, but only those that are validated are added to the
product Knowledge Base article.