Upload
anjinayulu-anji
View
194
Download
2
Embed Size (px)
DESCRIPTION
buk of wcf
Citation preview
Resource Links for 70-513 WCF Certification Exam
1 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Creating Services (20%)
Create service and operation contracts. This objective may include but is not limited to: one-way,
duplex, and request reply; creating and specifying fault contracts; configuration-based contracts;
exposing service metadata; selecting serialization (e.g., data contract serializer vs. XML
serializer)This objective does not include: designing service and operation contracts;
transactions, instantiation, security-related attributes
Designing Service Contracts
This topic describes what service contracts are, how they are defined, what operations are
available (and the implications for the underlying message exchanges), what data types are used,
and other issues that help you design operations that properly satisfy the requirements of your
scenario.
Creating a Service Contract
Services are groups of operations. To create a service contract you must model operations and
specify their grouping. In Windows Communication Foundation (WCF) applications, define the
operations by creating a method and marking it with the OperationContractAttribute attribute.
Then, to create a service contract, group together your operations, either by declaring them
within an interface marked with the ServiceContractAttribute attribute, or by defining them in a
class marked with the same attribute. (For a basic example, see How to: Define a Windows
Communication Foundation Service Contract.)
Any methods that do not have a OperationContractAttribute attribute are not service
operations and are not exposed for use by clients of WCF services. Like any managed method,
they can only be called by objects within their declared access scope.
In a similar manner, it is also valid to create a service contract class or interface that declares no
service operationsthe effect is the same as a class or interface with no methods. Any services
built using a contract of this type expose no operations for clients to use. This topic describes the
following decision points when designing a service contract:
Whether to use classes or interfaces.
How to specify the data types you want to exchange.
The types of exchange patterns you can use.
Resource Links for 70-513 WCF Certification Exam
2 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Whether you can make explicit security requirements part of the contract.
The restrictions for operation inputs and outputs.
Classes or Interfaces
Both classes and interfaces represent a grouping of functionality and, therefore, both can be used
to define a WCF service contract. However, it is recommended that you use interfaces because
they directly model service contracts. Without an implementation, interfaces do no more than
define a grouping of methods with certain signatures. Likewise, a service contract without an
implementation defines a grouping of operations with certain signatures. Implement a service
contract interface and you have implemented a WCF service.
All the benefits of managed interfaces apply to service contract interfaces:
Service contract interfaces can extend any number of other service contract interfaces.
A single class can implement any number of service contracts by implementing those service contract
interfaces.
You can modify the implementation of a service contract by changing the interface implementation, while
the service contract remains the same.
You can version your service by implementing the old interface and the new one. Old clients connect to
the original version, while newer clients can connect to the newer version.
Note:
When inheriting from other service contract interfaces, you cannot override operation properties, such as
the name or namespace. If you attempt to do so, you create a new operation in the current service
contract.
For an example of using an interface to create a service contract, see How to: Create a Service
with a Contract Interface.
You can, however, use a class to define a service contract and implement that contract at the
same time. The advantage of creating your services by applying ServiceContractAttribute and
OperationContractAttribute directly to the class and the methods on the class, respectively, is
speed and simplicity. The disadvantages are that managed classes do not support multiple
inheritance, and as a result they can only implement one service contract at a time. In addition,
any modification to the class or method signatures modifies the public contract for that service,
which can prevent unmodified clients from using your service. For more information, see
Implementing Service Contracts.
Resource Links for 70-513 WCF Certification Exam
3 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
For an example that uses a class to create a service contract and implements it at the same time,
see How to: Create a Windows Communication Foundation Contract with a Class.
At this point, you should understand the difference between defining your service contract by
using an interface and by using a class. The next step is deciding what data can be passed back
and forth between a service and its clients.
Parameters and Return Values
Each operation has a return value and a parameter, even if these are void. However, unlike a
local method, in which you can pass references to objects from one object to another, service
operations do not pass references to objects. Instead, they pass copies of the objects.
This is significant because each type used in a parameter or return value must be serializable;
that is, it must be possible to convert an object of that type into a stream of bytes and from a
stream of bytes into an object.Primitive types are serializable by default, as are many types in the
.NET Framework.
Note:
The value of the parameter names in the operation signature are part of the contract and are case sensitive.
If you want to use the same parameter name locally but modify the name in the published metadata, see
the System.ServiceModel.MessageParameterAttribute.
Data Contracts
Service-oriented applications like Windows Communication Foundation (WCF) applications are
designed to interoperate with the widest possible number of client applications on both Microsoft
and non-Microsoft platforms. For the widest possible interoperability, it is recommended that
you mark your types with the DataContractAttribute and DataMemberAttribute attributes to
create a data contract, which is the portion of the service contract that describes the data that your
service operations exchange.
Data contracts are opt-in style contracts: No type or data member is serialized unless you
explicitly apply the data contract attribute. Data contracts are unrelated to the access scope of the
managed code: Private data members can be serialized and sent elsewhere to be accessed
publicly. (For a basic example of a data contract, see How to: Create a Basic Data Contract for a
Class or Structure.) WCF handles the definition of the underlying SOAP messages that enable
the operation's functionality as well as the serialization of your data types into and out of the
Resource Links for 70-513 WCF Certification Exam
4 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
body of the messages. As long as your data types are serializable, you do not need to think about
the underlying message exchange infrastructure when designing your operations.
Although the typical WCF application uses the DataContractAttribute and
DataMemberAttribute attributes to create data contracts for operations, you can use other
serialization mechanisms. The standard ISerializable, SerializableAttribute and IXmlSerializable
mechanisms all work to handle the serialization of your data types into the underlying SOAP
messages that carry them from one application to another. You can employ more serialization
strategies if your data types require special support. For more information about the choices for
serialization of data types in WCF applications, see Specifying Data Transfer in Service
Contracts.It is important to note that the CLR names in the definition of a Service Contract and
its operations are significant and should not be confused. To avoid confusion of types used to
define a Service Contract use the ObfuscationAttribute and ObfuscateAssemblyAttribute
attributes.
Mapping Parameters and Return Values to Message Exchanges
Service operations are supported by an underlying exchange of SOAP messages that transfer
application data back and forth, in addition to the data required by the application to support
certain standard security, transaction, and session-related features. Because this is the case, the
signature of a service operation dictates a certain underlying message exchange pattern (MEP)
that can support the data transfer and the features an operation requires. You can specify three
patterns in the WCF programming model: request/reply, one-way, and duplex message patterns.
Request/Reply
A request/reply pattern is one in which a request sender (a client application) receives a reply
with which the request is correlated. This is the default MEP because it supports both an
operation in which one or more parameters are passed to the operation and a return and one or
more out values that the operation passes back to the caller. For example, the following C# code
example shows a basic service operation that takes one string and returns a string.
C#
[OperationContractAttribute]
string Hello(string greeting);
The following is the equivalent Visual Basic code.
VB
Resource Links for 70-513 WCF Certification Exam
5 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Function Hello (ByVal greeting AsString) AsString
This operation signature dictates the form of underlying message exchange. If no correlation
existed, WCF cannot determine for which operation the return value is intended.
Note that unless you specify a different underlying message pattern, even service operations that
return void (Nothing in Visual Basic) are request/reply message exchanges. The result for your
operation is that unless a client invokes the operation asynchronously, the client stops processing
until the return message is received, even though that message is empty in the normal case. The
following C# code example shows an operation that does not return until the client has received
an empty message in response.
C#
[OperationContractAttribute]
void Hello(string greeting);
The following is the equivalent Visual Basic code.
VB
Sub Hello (ByVal greeting AsString)
The preceding example can slow client performance and responsiveness if the operation takes a
long time to perform, but there are advantages to request/reply operations even when they return
void. The most obvious one is that SOAP faults can be returned in the response message, which
indicates that some service-related error condition has occurred, whether in communication or
processing. SOAP faults that are specified in a service contract are passed to the client
application as a FaultException object, where the type parameter is the type specified in the
service contract. This makes notifying clients about error conditions in WCF services easy. For
more information about exceptions, SOAP faults, and error handling, see Specifying and
Handling Faults in Contracts and Services. To see an example of a request/reply service and
client, see How to: Create a Request-Reply Contract. For more information about issues with the
request-reply pattern, see Request-Reply Services.
One-way
If the client of a WCF service application should not wait for the operation to complete and does
not process SOAP faults, the operation can specify a one-way message pattern. A one-way
operation is one in which a client invokes an operation and continues processing after WCF
Resource Links for 70-513 WCF Certification Exam
6 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
writes the message to the network. Typically this means that unless the data being sent in the
outbound message is extremely large the client continues running almost immediately (unless
there is an error sending the data). This type of message exchange pattern supports event-like
behavior from a client to a service application.
A message exchange in which one message is sent and none are received cannot support a
service operation that specifies a return value other than void; in this case an
InvalidOperationException exception is thrown.
No return message also means that there can be no SOAP fault returned to indicate any errors in
processing or communication. (Communicating error information when operations are one-way
operations requires a duplex message exchange pattern.)
To specify a one-way message exchange for an operation that returns void, set the IsOneWay
property to true, as in the following C# code example.
C#
[OperationContractAttribute(IsOneWay=true)]
void Hello(string greeting);
The following is the equivalent Visual Basic code.
VB
Sub Hello (ByVal greeting AsString)
This method is identical to the preceding request/reply example, but setting the IsOneWay
property to true means that although the method is identical, the service operation does not send
a return message and clients return immediately once the outbound message has been handed to
the channel layer. For an example, see How to: Create a One-Way Contract. For more
information about the one-way pattern, see One-Way Services.
Duplex
A duplex pattern is characterized by the ability of both the service and the client to send
messages to each other independently whether using one-way or request/reply messaging. This
form of two-way communication is useful for services that must communicate directly to the
client or for providing an asynchronous experience to either side of a message exchange,
including event-like behavior.
The duplex pattern is slightly more complex than the request/reply or one-way patterns because
of the additional mechanism for communicating with the client.
Resource Links for 70-513 WCF Certification Exam
7 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
To design a duplex contract, you must also design a callback contract and assign the type of that
callback contract to the CallbackContract property of the ServiceContractAttribute attribute
that marks your service contract.
To implement a duplex pattern, you must create a second interface that contains the method
declarations that are called on the client.
For an example of creating a service, and a client that accesses that service, see How to: Create a
Duplex Contract and How to: Access Services with a Duplex Contract. For a working sample,
see Service Contract: Duplex. For more information about issues using duplex contracts, see
Duplex Services.
Caution:
When a service receives a duplex message, it looks at the ReplyTo element in that incoming message to
determine where to send the reply. If the channel that is used to receive the message is not secured, then
an untrusted client could send a malicious message with a target machine's ReplyTo, leading to a denial
of service (DOS) of that target machine.
Out and Ref Parameters
In most cases, you can use in parameters (ByVal in Visual Basic) and out and ref parameters
(ByRef in Visual Basic). Because both out and ref parameters indicate that data is returned from
an operation, an operation signature such as the following specifies that a request/reply operation
is required even though the operation signature returns void.
C#
[ServiceContractAttribute]
publicinterface IMyContract
{
[OperationContractAttribute]
publicvoid PopulateData(ref CustomDataType data);
}
The following is the equivalent Visual Basic code.
[Visual Basic]
_
Public Interface IMyContract
_
Public Sub PopulateData(ByRef data As CustomDataType)
Resource Links for 70-513 WCF Certification Exam
8 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
End Interface
The only exceptions are those cases in which your signature has a particular structure. For
example, you can use the NetMsmqBinding binding to communicate with clients only if the
method used to declare an operation returns void; there can be no output value, whether it is a
return value, ref, or out parameter.In addition, using out or ref parameters requires that the
operation have an underlying response message to carry back the modified object. If your
operation is a one-way operation, an InvalidOperationException exception is thrown at
runtime.
Specify Message Protection Level on the Contract
When designing your contract, you must also decide the message protection level of services that
implement your contract. This is necessary only if message security is applied to the binding in
the contract's endpoint. If the binding has security turned off (that is, if the system-provided
binding sets the System.ServiceModel.SecurityMode to the value
System.ServiceModel.SecurityMode.None) then you do not have to decide on the message
protection level for the contract. In most cases, system-provided bindings with message-level
security applied provide a sufficient protection level and you do not have to consider the
protection level for each operation or for each message.The protection level is a value that
specifies whether the messages (or message parts) that support a service are signed, signed and
encrypted, or sent without signatures or encryption. The protection level can be set at various
scopes: At the service level, for a particular operation, for a message within that operation, or a
message part. Values set at one scope become the default value for smaller scopes unless
explicitly overridden. If a binding configuration cannot provide the required minimum protection
level for the contract, an exception is thrown. And when no protection level values are explicitly
set on the contract, the binding configuration controls the protection level for all messages if the
binding has message security. This is the default behavior.
Note:
Deciding whether to explicitly set various scopes of a contract to less than the full protection level of
System.Net.Security.ProtectionLevel.EncryptAndSign is generally a decision that trades some degree of
security for increased performance. In these cases, your decisions must revolve around your operations
and the value of the data they exchange. For more information, see Securing Services.
Resource Links for 70-513 WCF Certification Exam
9 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
For example, the following code example does not set either the ProtectionLevel or the
ProtectionLevel property on the contract.
C#
[ServiceContract]
publicinterface ISampleService
{
[OperationContractAttribute]
publicstring GetString();
[OperationContractAttribute]
publicint GetInt();
}
The following is the equivalent Visual Basic code.
[Visual Basic]
_
Public Interface ISampleService
_
Public Function GetString()As String
_
Public Function GetData() As Integer
End Interface
When interacting with an ISampleService implementation in an endpoint with a default
WSHttpBinding (the default System.ServiceModel.SecurityMode, which is Message), all
messages are encrypted and signed because this is the default protection level. However, when
an ISampleService service is used with a default BasicHttpBinding (the default SecurityMode,
which is None), all messages are sent as text because there is no security for this binding and so
the protection level is ignored (that is, the messages are neither encrypted nor signed). If the
SecurityMode was changed to Message, then these messages would be encrypted and signed
(because that would now be the binding's default protection level).If you want to explicitly
specify or adjust the protection requirements for your contract, set the ProtectionLevel property
(or any of the ProtectionLevel properties at a smaller scope) to the level your service contract
requires. In this case, using an explicit setting requires the binding to support that setting at a
Resource Links for 70-513 WCF Certification Exam
10 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
minimum for the scope used. For example, the following code example specifies one
ProtectionLevel value explicitly, for the GetGuid operation.
[C#]
[ServiceContract]
public interface IExplicitProtectionLevelSampleService
{
[OperationContractAttribute]
public string GetString();
[OperationContractAttribute(ProtectionLevel=ProtectionLevel.None)]
public int GetInt();
[OperationContractAttribute(ProtectionLevel=ProtectionLevel.EncryptAndSign)]
public int GetGuid();
}
The following is the equivalent Visual Basic code.
[Visual Basic]
_
Public Interface IExplicitProtectionLevelSampleService
_
Public Function GetString() As String
End Function
_
Public Function GetInt() As Integer
End Function
_
Public Function GetGuid() As Integer
End Function
End Interface
A service that implements this IExplicitProtectionLevelSampleService contract and has an endpoint
that uses the default WSHttpBinding (the default System.ServiceModel.SecurityMode, which
is Message) has the following behavior:
The GetString operation messages are encrypted and signed.
The GetInt operation messages are sent as unencrypted and unsigned (that is, plain) text.
The GetGuid operation System.Guid is returned in a message that is encrypted and signed.
Resource Links for 70-513 WCF Certification Exam
11 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
For more information about protection levels and how to use them, see Understanding Protection
Level. For more information about security, see Securing Services.
Other Operation Signature Requirements
Some application features require a particular kind of operation signature. For example, the
NetMsmqBinding binding supports durable services and clients, in which an application can
restart in the middle of communication and pick up where it left off without missing any
messages. (For more information, see Queues in Windows Communication Foundation.)
However, durable operations must take only one in parameter and have no return value.
Another example is the use of Stream types in operations. Because the Stream parameter
includes the entire message body, if an input or an output (that is, ref parameter, out parameter,
or return value) is of type Stream, then it must be the only input or output specified in your
operation. In addition, the parameter or return type must be either Stream,
System.ServiceModel.Channels.Message, or System.Xml.Serialization.IXmlSerializable. For
more information about streams, see Large Data and Streaming.
Names, Namespaces, and Obfuscation
The names and namespaces of the .NET types in the definition of contracts and operations are
significant when contracts are converted into WSDL and when contract messages are created and
sent. Therefore, it is strongly recommended that service contract names and namespaces are
explicitly set using the Name and Namespace properties of all supporting contract attributes
such as the ServiceContractAttribute, OperationContractAttribute, DataContractAttribute,
DataMemberAttribute, and other contract attributes.
One result of this is that if the names and namespaces are not explicitly set, the use of IL
obfuscation on the assembly alters the contract type names and namespaces and results in
modified WSDL and wire exchanges that typically fail. If you do not set the contract names and
namespaces explicitly but do intend to use obfuscation, use the ObfuscationAttribute and
ObfuscateAssemblyAttribute attributes to prevent the modification of the contract type names
and namespaces.
Specifying and Handling Faults in Contracts
and Services
Resource Links for 70-513 WCF Certification Exam
12 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Windows Communication Foundation (WCF) applications handle error situations by mapping
managed exception objects to SOAP fault objects and SOAP fault objects to managed exception
objects. The topics in this section discuss how to design contracts to expose error conditions as
custom SOAP faults, how to return such faults as part of service implementation, and how clients
catch such faults.
Error Handling Overview
In all managed applications, processing errors are represented by Exception objects. In SOAP-
based applications such as WCF applications, service methods communicate processing error
information using SOAP fault messages. SOAP faults are message types that are included in the
metadata for a service operation and therefore create a fault contract that clients can use to make
their operation more robust or interactive. In addition, because SOAP faults are expressed to
clients in XML form, it is a highly interoperable type system that clients on any SOAP platform
can use, increasing the reach of your WCF application.
Because WCF applications run under both types of error systems, any managed exception
information that is sent to the client must be converted from exceptions into SOAP faults on the
service, sent, and converted from SOAP faults to fault exceptions in WCF clients. In the case of
duplex clients, client contracts can also send SOAP faults back to a service. In either case, you
can use the default service exception behaviors, or you can explicitly control whetherand
howexceptions are mapped to fault messages.
Two types of SOAP faults can be sent: declared and undeclared. Declared SOAP faults are those
in which an operation has a System.ServiceModel.FaultContractAttribute attribute that specifies
a custom SOAP fault type. Undeclared SOAP faults are not specified in the contract for an
operation.
It is strongly recommended that service operations declare their faults by using the
FaultContractAttribute attribute to formally specify all SOAP faults that a client can expect to
receive in the normal course of an operation. It is also recommended that you return in a SOAP
fault only the information that a client must know to minimize information disclosure.
Typically, services (and duplex clients) take the following steps to successfully integrate error
handling into their applications:
Map exception conditions to custom SOAP faults.
Clients and services send and receive SOAP faults as exceptions.
Resource Links for 70-513 WCF Certification Exam
13 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
In addition, WCF clients and services can use undeclared soap faults for debugging purposes and
can extend the default error behavior. The following sections discuss these tasks and concepts.
Map Exceptions to SOAP Faults
The first step in creating an operation that handles error conditions is to decide under what
conditions a client application should be informed about errors. Some operations have error
conditions specific to their functionality. For example, a PurchaseOrder operation might return
specific information to customers who are no longer permitted to initiate a purchase order. In
other cases, such as a Calculator service, a more general MathFault SOAP fault may be able to
describe all error conditions across an entire service. Once the error conditions of clients of your
service are identified, a custom SOAP fault can be constructed and the operation can be marked
as returning that SOAP fault when its corresponding error condition arises.
For more information about this step of developing your service or client, see Defining and
Specifying Faults.Clients and Services Handle SOAP Faults as ExceptionsIdentifying operation
error conditions, defining custom SOAP faults, and marking those operations as returning those
faults are the first steps in successful error handling in WCF applications. The next step is to
properly implement the sending and receiving of these faults. Typically services send faults to
inform client applications about error conditions, but duplex clients can also send SOAP faults to
services. For more information, see Sending and Receiving Faults.Undeclared SOAP Faults and
DebuggingDeclared SOAP faults are extremely useful for building robust, interoperable,
distributed applications. However, in some cases it is useful for a service (or duplex client) to
send an undeclared SOAP fault, one that is not mentioned in the Web Services Description
Language (WSDL) for that operation. For example, when developing a service, unexpected
situations can occur in which it is useful for debugging purposes to send information back to the
client. In addition, you can set the ServiceBehaviorAttribute.IncludeExceptionDetailInFaults
property or the ServiceDebugBehavior.IncludeExceptionDetailInFaults property to true to permit
WCF clients to obtain information about internal service operation exceptions. Both sending
individual faults and setting the debugging behavior properties are described in Sending and
Receiving Faults.
Important
Because managed exceptions can expose internal application information, setting
Resource Links for 70-513 WCF Certification Exam
14 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
ServiceBehaviorAttribute.IncludeExceptionDetailInFaults or
ServiceDebugBehavior.IncludeExceptionDetailInFaults to true can permit WCF clients to obtain
information about internal service operation exceptions, including personally identifiable or
other sensitive information.
Therefore, setting ServiceBehaviorAttribute.IncludeExceptionDetailInFaults or
ServiceDebugBehavior.IncludeExceptionDetailInFaults to true is recommended only as a way to
temporarily debug a service application. In addition, the WSDL for a method that returns
unhandled managed exceptions in this way does not contain the contract for the
FaultException of type ExceptionDetail. Clients must expect the possibility of an
unknown SOAP fault (returned to WCF clients as System.ServiceModel.FaultException objects)
to obtain the debugging information properly.
Customizing Error Handling with IErrorHandlerIf you have special requirements to either customize the
response message to the client when an application-level exception happens or perform some custom
processing after the response message is returned, implement the
System.ServiceModel.Dispatcher.IErrorHandler interface. Fault Serialization IssuesWhen deserializing a
fault contract, WCF first attempts to match the fault contract name in the SOAP message with the fault
contract type. If it cannot find an exact match it will then search the list of available fault contracts in
alphabetical order for a compatible type. If two fault contracts are compatible types (one is a subclass of
another, for example) the wrong type may be used to de-serialize the fault. This only occurs if the fault
contract does not specify a name, namespace, and action. To prevent this issue from occurring, always
fully qualify fault contracts by specifying the name, namespace, and action attributes. Additionally if you
have defined a number of related fault contracts derived from a shared base class, make sure to mark any
new members with [DataMember(IsRequired=true)]. For more information on this IsRequired attribute
see, DataMemberAttribute. This will prevent a base class from being a compatible type and force the fault
to be deserialized into the correct derived type.
Metadata
The Windows Communication Foundation (WCF) provides an infrastructure for exporting,
publishing, retrieving, and importing service metadata. WCF services use metadata to describe
how to interact with the service's endpoints so that tools, such as Svcutil.exe, can automatically
generate client code for accessing the service.
Resource Links for 70-513 WCF Certification Exam
15 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
In This Section
Metadata Architecture Overview
A high-level overview of metadata architecture.
Metadata Formats
Describes the different metadata formats.
Exporting and Importing Metadata
Describes how to export and import metadata.
Publishing Metadata
Describes how WCF publishes metadata.
Retrieving Metadata
Describes the different ways to retrieve metadata.
Using Metadata
Describes different ways to use service metadata.
Security Considerations with Metadata
Describes important security considerations when dealing with service metadata.
Metadata Architecture Overview
Windows Communication Foundation (WCF) provides a rich infrastructure for exporting,
publishing, retrieving, and importing service metadata. WCF services use metadata to describe
how to interact with the service's endpoints so that tools, such as Svcutil.exe, can automatically
generate client code for accessing the service.Most of the types that make up the WCF metadata
infrastructure reside in the System.ServiceModel.Description namespace. WCF uses the
ServiceEndpoint class to describe endpoints in a service. You can use WCF to generate metadata
for service endpoints or import service metadata to generate ServiceEndpoint instances.
WCF represents the metadata for a service as an instance of the MetadataSet type, the structure
of which is strongly tied to the metadata serialization format defined in WS-MetadataExchange.
The MetadataSet type bundles the actual service metadata, such as Web Services Description
Language (WSDL) documents, XML schema documents, or WS-Policy expressions, as a
collection of MetadataSection instances. Each
System.ServiceModel.Description.MetadataSection instance contains a specific metadata
Resource Links for 70-513 WCF Certification Exam
16 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
dialect and an identifier. A System.ServiceModel.Description.MetadataSection can contain
the following items in its System.ServiceModel.Description.MetadataSection.Metadata property:
Raw metadata.
A MetadataReference instance.
A MetadataLocation instance.
A System.ServiceModel.Description.MetadataReference instances point to another metadata
exchange (MEX) endpoint and System.ServiceModel.Description.MetadataLocation instances
point to a metadata document using an HTTP URL. WCF supports using WSDL documents to
describe service endpoints, service contracts, bindings, message exchange patterns, messages and
fault messages implemented by a service. Data types used by the service are described in WSDL
documents using XML schema. For more information, see Schema Import and Export. You can
use WCF to export and import WSDL extensions for service behavior, contract behaviors, and
binding elements that extend the functionality of a service. For more information, see Exporting
Custom Metadata for a WCF Extension.
Exporting Service Metadata
In WCF, metadata export is the process of describing service endpoints and projecting them into
a parallel, standardized representation that clients can use to understand how to use the service.
To export metadata from ServiceEndpoint instances, use an implementation of the
MetadataExporter abstract class. A System.ServiceModel.Description.MetadataExporter
implementation generates metadata that is encapsulated in a MetadataSet instance.
The System.ServiceModel.Description.MetadataExporter class provides a framework for
generating policy expressions that describe the capabilities and requirements of an endpoint
binding and its associated operations, messages, and faults. These policy expressions are
captured in a PolicyConversionContext instance. A
System.ServiceModel.Description.MetadataExporter implementation can then attach these
policy expressions to the metadata it generates.The
System.ServiceModel.Description.MetadataExporter calls into each
System.ServiceModel.Channels.BindingElement that implements the IPolicyExportExtension
interface in the binding of a ServiceEndpoint when generating a PolicyConversionContext
object for the System.ServiceModel.Description.MetadataExporter implementation to use.
Resource Links for 70-513 WCF Certification Exam
17 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
You can export new policy assertions by implementing the IPolicyExportExtension interface
on your custom implementations of the BindingElement type. The WsdlExporter type is the
implementation of the System.ServiceModel.Description.MetadataExporter abstract class
included with WCF. The WsdlExporter type generates WSDL metadata with attached policy
expressions. To export custom WSDL metadata or WSDL extensions for endpoint behaviors,
contract behaviors, or binding elements in a service endpoint, you can implement the
IWsdlExportExtension interface. The WsdlExporter looks at a ServiceEndpoint instance for
binding elements, operation behaviors, contract behaviors, and endpoint behaviors that
implement the IWsdlExportExtension interface when generating the WSDL document.
Publishing Service Metadata
WCF services publish metadata by exposing one or more metadata endpoints. Publishing service
metadata makes service metadata available using standardized protocols, such as MEX and
HTTP/GET requests. Metadata endpoints are similar to other service endpoints in that they have
an address, a binding, and a contract. You can add metadata endpoints to a service host in
configuration or in code. To publish metadata endpoints for a WCF service, you must first add an
instance of the ServiceMetadataBehavior service behavior to the service. Adding a
System.ServiceModel.Description.ServiceMetadataBehavior instance to your service
augments your service with the ability to publish metadata by exposing one or more metadata
endpoints. Once you add the System.ServiceModel.Description.ServiceMetadataBehavior
service behavior you can then expose metadata endpoints that support the MEX protocol or
metadata endpoints that respond to HTTP/GET requests. To add metadata endpoints that use the
MEX protocol, add service endpoints to your service host that use the service contract named
IMetadataExchange.WCF defines the IMetadataExchange interface that has this service contract
name. WS-MetadataExchange endpoints, or MEX endpoints, can use one of the four default
bindings exposed by the static factory methods on the MetadataExchangeBindings class to match
the default bindings used by WCF tools, such as Svcutil.exe. You can also configure MEX
metadata endpoints using a custom binding.The ServiceMetadataBehavior uses a
System.ServiceModel.Description.WsdlExporter to export metadata for all service endpoints
in your service. For more information about exporting metadata from a service, see Exporting
and Importing Metadata.The ServiceMetadataBehavior augments your service host by adding a
Resource Links for 70-513 WCF Certification Exam
18 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
ServiceMetadataExtension instance as an extension to your service host. The
System.ServiceModel.Description.ServiceMetadataExtension provides the implementation
for the metadata publishing protocols. You can also use the
System.ServiceModel.Description.ServiceMetadataExtension to get the service's metadata at
runtime by accessing the Metadata property.
Caution:
If you add a MEX endpoint in your application configuration file and then attempt to add the
ServiceMetadataBehavior to your service host in code you get the following exception:
System.InvalidOperationException: The contract name 'IMetadataExchange' could not be found in the list
of contracts implemented by the service Service1. Add a ServiceMetadataBehavior to the configuration
file or to the ServiceHost directly to enable support for this contract.
You can work around this issue by either adding the ServiceMetadataBehavior in the configuration file
or adding both the endpoint and ServiceMetadataBehavior in code.
For an example of adding ServiceMetadataBehavior in an application configuration file, see the Getting
Started Sample. For an example of adding ServiceMetadataBehavior in code, see the Self-Host sample.
Caution:
When publishing metadata for a service that exposes two different service contracts in which each contain
an operation of the same name an exception is thrown. For example, if you have a service that exposes a
service contract called ICarService that has an operation Get(Car c) and the same service exposes a
service contract called IBookService that has an operation Get(Book b), an exception is thrown or an
error message is displayed when generating the service's metadata. To work around this issue do one of
the following:
Rename one of the operations.
Set the Name to a different name.
Set one of the operations' namespaces to a different namespace using the Namespace property.
Retrieving Service Metadata
WCF can retrieve service metadata using standardized protocols such as WS-MetadataExchange
and HTTP. Both of these protocols are supported by the MetadataExchangeClient type. You
retrieve service metadata using the
System.ServiceModel.Description.MetadataExchangeClient type by providing an address and
an optional binding. The binding used by a
Resource Links for 70-513 WCF Certification Exam
19 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
System.ServiceModel.Description.MetadataExchangeClient instance can be one of the
default bindings from the MetadataExchangeBindings static class, a user-supplied binding, or a
binding loaded from an endpoint configuration for the IMetadataExchange contract. The
System.ServiceModel.Description.MetadataExchangeClient can also resolve HTTP URL
references to metadata using the HttpWebRequest type.By default, a
System.ServiceModel.Description.MetadataExchangeClient instance is tied to a single
ChannelFactoryBase instance. You can change or replace the ChannelFactoryBase instance
used by a System.ServiceModel.Description.MetadataExchangeClient by overriding the
GetChannelFactory virtual method. Similarly, you can change or replace the
System.Net.HttpWebRequest instance used by a
System.ServiceModel.Description.MetadataExchangeClient to make HTTP/GET requests by
overriding the
System.ServiceModel.Description.MetadataExchangeClient.GetWebRequest(System.Uri,System
.String,System.String) virtual method.You can retrieve service metadata using WS-
MetadataExchange or HTTP/GET requests by using the Svcutil.exe tool and passing the
/target:metadata switch and an address. Svcutil.exe downloads the metadata at the specified
address and saves the files to disk. Svcutil.exe uses a
System.ServiceModel.Description.MetadataExchangeClient instance internally and loads an
MEX endpoint configuration (from the application configuration file) whose name matches the
scheme of the address passed to Svcutil.exe, if one exists. Otherwise, Svcutil.exe defaults to
using one of the bindings defined by the MetadataExchangeBindings static factory type.
Importing Service Metadata
In WCF, metadata import is the process of generating an abstract representation of a service or
its component parts from its metadata. For example, WCF can import ServiceEndpoint
instances, Binding instances or ContractDescription instances from a WSDL document for a
service. To import service metadata in WCF, use an implementation of the MetadataImporter
abstract class. Types that derive from the
System.ServiceModel.Description.MetadataImporter class implement support for importing
metadata formats that take advantage of the WS-Policy import logic in WCF.
Resource Links for 70-513 WCF Certification Exam
20 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
A System.ServiceModel.Description.MetadataImporter implementation collects the policy
expressions attached to the service metadata in a PolicyConversionContext object. The
System.ServiceModel.Description.MetadataImporter then processes the policies as part of
importing the metadata by calling the implementations of the IPolicyImportExtension interface
in the PolicyImportExtensions property.
You can add support for importing new policy assertions to a
System.ServiceModel.Description.MetadataImporter by adding your own implementation of
the IPolicyImportExtension interface to the PolicyImportExtensions collection on a
System.ServiceModel.Description.MetadataImporter instance. Alternatively, you can register
your policy import extension in your client application configuration file.
The System.ServiceModel.Description.WsdlImporter type is the implementation of the
System.ServiceModel.Description.MetadataImporter abstract class included with WCF. The
System.ServiceModel.Description.WsdlImporter type imports WSDL metadata with attached
policies that are bundled in a MetadataSet object.
You can add support for importing WSDL extensions by implementing the
IWsdlImportExtension interface and then adding your implementation to the
WsdlImportExtensions property on your System.ServiceModel.Description.WsdlImporter
instance. The System.ServiceModel.Description.WsdlImporter can also load implementations
of the System.ServiceModel.Description.IWsdlImportExtension interface registered in your
client application configuration file.
Dynamic Bindings
You can dynamically update the binding that you use to create a channel to a service endpoint in
the event that the binding for the endpoint changes or you want to create a channel to an endpoint
that uses the same contract but has a different binding. You can use the MetadataResolver static
class to retrieve and import metadata at runtime for service endpoints that implement a specific
contract. You can then use the imported System.ServiceModel.Description.ServiceEndpoint
objects to create a client or channel factory to the desired endpoint.
Metadata Formats
Resource Links for 70-513 WCF Certification Exam
21 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Windows Communication Foundation (WCF) supports the metadata formats in the following
table.
Metadata Specifications and Usage
Protocol Specification and usage
WSDL 1.1
Web Services Description Language (WSDL) 1.1
WCF uses Web Services Description Language (WSDL) to describe
services.
XML Schema
XML Schema Part 2: Datatypes Second Edition and XML Schema Part
1: Structures Second Edition
WCF uses the XML Schema to describe data types used in messages.
WS Policy
Web Services Policy 1.2 - Framework (WS-Policy)
Web Services Policy 1.5 - Framework
WCF uses the WS-Policy 1.2 or 1.5 specifications with domain-specific
assertions to describe service requirements and capabilities.
WS Policy
Attachments
Web Services Policy 1.2 - Attachment (WS-PolicyAttachment)
WCF implements WS-Policy Attachments to attach policy expressions
at various scopes in WSDL.
WS Metadata
Exchange
Web Services Metadata Exchange (WS-MetadataExchange) version 1.1
WCF implements WS-MetadataExchange to retrieve XML Schema,
WSDL, and WS-Policy.
WS Addressing
Binding for WSDL
Web Services Addressing 1.0 - WSDL Binding
WCF implements WS-Addressing Binding for WSDL to attach
addressing information in WSDL.
Exporting and Importing Metadata
In Windows Communication Foundation (WCF), exporting metadata is the process of describing
service endpoints and projecting them into a parallel, standardized representation that clients can
use to understand how to use the service. Importing service metadata is the process of generating
ServiceEndpoint instances or parts from service metadata.
Resource Links for 70-513 WCF Certification Exam
22 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Exporting Metadata
To export metadata from System.ServiceModel.Description.ServiceEndpoint instances, use an
implementation of the MetadataExporter abstract class. The WsdlExporter type is the
implementation of the MetadataExporter abstract class included with WCF.
The System.ServiceModel.Description.WsdlExporter type generates Web Services
Description Language (WSDL) metadata with attached policy expressions encapsulated in a
MetadataSet instance. You can use a System.ServiceModel.Description.WsdlExporter
instance to iteratively export metadata for ContractDescription objects and ServiceEndpoint
objects. You can also export a collection of ServiceEndpoint objects and associate them with a
specific service name.
Note:
You can only use the WsdlExporter to export metadata from ContractDescription instances
that contain common language runtime (CLR) type information, such as a ContractDescription
instance created using the ContractDescription.GetContract method or created as part of the
ServiceDescription for a ServiceHost instance. You cannot use the WsdlExporter to export
metadata from ContractDescription instances imported from service metadata or constructed
without type information.
Importing Metadata
Importing WSDL Documents
To import service metadata in WCF, use an implementation of the MetadataImporter abstract
class. The System.ServiceModel.Description.WsdlImporter type is the implementation of the
MetadataImporter abstract class included with WCF. The WsdlImporter type imports WSDL
metadata with attached policies bundled in a MetadataSet object.
The WsdlImporter type gives you control over how to import the metadata. You can import all
of the endpoints, all of the bindings, or all of the contracts. You can import all of the endpoints
associated with a specific WSDL service, binding, or port type. You can also import the endpoint
for a specific WSDL port, the binding for a specific WSDL binding or the contract for a specific
WSDL port type.
Resource Links for 70-513 WCF Certification Exam
23 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
The WsdlImporter also exposes a KnownContracts property that allows you to specify a set of
contracts that do not need to be imported. The WsdlImporter uses the contracts in the
KnownContracts property instead of importing a contract with the same qualified name from
the metadata.
Importing Policies
The WsdlImporter type collects the policy expressions attached to the message, operation, and
endpoint policy subjects and then uses the IPolicyImportExtension implementations in the
PolicyImportExtensions collection to import the policy expressions.The policy import logic
automatically handles policy references to policy expressions in the same WSDL document and
is identified with a wsu:Id or xml:id attribute. The policy import logic protects applications
against circular policy references by limiting the size of a policy expression to 4096 nodes,
where a node is a one of the following elements: wsp:Policy, wsp:All, wsp:ExactlyOne,
wsp:policyReference.The policy import logic also automatically normalizes policy expressions.
Nested policy expressions and the wsp:Optional attribute are not normalized. The amount of
normalization processing done is limited to 4096 steps, where each step yields a policy assertion,
or a child element of a wsp:ExactlyOne element.The WsdlImporter type tries up to 32
combinations of policy alternatives attached to the different WSDL policy subjects. If no
combination imports cleanly, the first combination is used to construct a partial custom binding.
Error Handling
Both the MetadataExporter and the MetadataImporter types expose an Errors property that
can contain a collection of error and warning messages encountered during the export and import
processes, respectively, that can be used when implementing tools.The WsdlImporter type
generally throws an exception for an exception caught during the import process and adds a
corresponding error to its Errors property. The ImportAllContracts, ImportAllBindings,
ImportAllEndpoints, and ImportEndpoints methods, however, do not throw these exceptions, so
you must check the Errors property to determine if any issues occurred when calling these
methods.The WsdlExporter type rethrows any exceptions caught during the export process.
These exceptions are not captured as errors in the Errors property. Once the WsdlExporter
throws an exception, it is in a faulted state and cannot be reused. The WsdlExporter does add
Resource Links for 70-513 WCF Certification Exam
24 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
warnings to its Errors property when an operation cannot be exported because it uses wildcard
actions and when duplicate binding names are encountered.
In This Section
How to: Import Metadata into Service Endpoints
Describes how to import downloaded metadata into description objects.
How to: Export Metadata from Service Endpoints
Describes how to export description objects into metadata.
ServiceDescription and WSDL Reference
Describes the mapping between the description objects and WSDL.
How to: Use Svcutil.exe to Export Metadata from Compiled Service Code
Describes the use of Svcutil.exe to export metadata for services, contracts, and data types in
compiled assemblies.
Data Contract Schema Reference
Describes the subset of the XML Schema (XSD) used by DataContractSerializer to describe
common language run-time (CLR) types for XML serialization.
Publishing Metadata
Windows Communication Foundation (WCF) services publish metadata by publishing one or
more metadata endpoints. Publishing service metadata makes the metadata available using
standardized protocols, such as WS-MetadataExchange (MEX) and HTTP/GET requests.
Metadata endpoints are similar to other service endpoints in that they have an address, a binding,
and a contract, and they can be added to a service host through configuration or imperative code.
Publishing Metadata Endpoints
To publish metadata endpoints for a WCF service, you first must add the
ServiceMetadataBehavior service behavior to the service. Adding a
System.ServiceModel.Description.ServiceMetadataBehavior instance allows your service to
expose metadata endpoints. Once you add the
System.ServiceModel.Description.ServiceMetadataBehavior service behavior, you can then
expose metadata endpoints that support the MEX protocol or that respond to HTTP/GET
requests.
Resource Links for 70-513 WCF Certification Exam
25 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
The System.ServiceModel.Description.ServiceMetadataBehavior uses a WsdlExporter to
export metadata for all service endpoints in your service. For more information about exporting
metadata from a service, see Exporting and Importing Metadata.
The System.ServiceModel.Description.ServiceMetadataBehavior adds a
ServiceMetadataExtension instance as an extension to your service host. The
System.ServiceModel.Description.ServiceMetadataExtension provides the implementation
for the metadata publishing protocols. You can also use the
System.ServiceModel.Description.ServiceMetadataExtension to get the service's metadata at
runtime by accessing the System.ServiceModel.Description.ServiceMetadataExtension.Metadata
property.
MEX Metadata Endpoints
To add metadata endpoints that use the MEX protocol, add service endpoints to your service host
that use the IMetadataExchange service contract. WCF includes an IMetadataExchange
interface with this service contract name that you can use as part of the WCF programming
model. WS-MetadataExchange endpoints, or MEX endpoints, can use one of the four default
bindings that the static factory methods expose on the MetadataExchangeBindings class to match
the default bindings used by WCF tools such as Svcutil.exe. You can also configure MEX
metadata endpoints using your own custom binding.
HTTP GET Metadata Endpoints
To add a metadata endpoint to your service that responds to HTTP/GET requests, set the
HttpGetEnabled property on the System.ServiceModel.Description.ServiceMetadataBehavior
to true. You can also configure a metadata endpoint that uses HTTPS by setting the
HttpsGetEnabled property on the
System.ServiceModel.Description.ServiceMetadataBehavior to true.
In This Section
How to: Publish Metadata for a Service Using a Configuration File
Demonstrates how to configure a WCF service to publish metadata so that clients can retrieve
the metadata using a WS-MetadataExchange or an HTTP/GET request using the ?wsdl query
string.
How to: Publish Metadata for a Service Using Code
Resource Links for 70-513 WCF Certification Exam
26 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Demonstrates how to enable metadata publishing for a WCF service in code so that clients can
retrieve the metadata using a WS-MetadataExchange or an HTTP/GET request using the ?wsdl
query string.
Retrieving Metadata
Metadata retrieval is the process of requesting and retrieving metadata from a metadata endpoint,
such as a WS-MetadataExchange (MEX) metadata endpoint or an HTTP/GET metadata
endpoint.
Retrieving Metadata from the Command Line Using
Svcutil.exe
You can retrieve service metadata using WS-MetadataExchange or HTTP/GET requests by
using the ServiceModel Metadata Utility Tool (Svcutil.exe) tool and passing the /target:metadata
switch and an address. Svcutil.exe downloads the metadata at the specified address and saves the
file to disk. Svcutil.exe uses a System.ServiceModel.Description.MetadataExchangeClient
instance internally and loads from configuration the IMetadataExchange endpoint configuration
whose name matches the scheme of the address passed to Svcutil.exe as input.
Retrieving Metadata Programmatically Using the
MetadataExchangeClient
Windows Communication Foundation (WCF) can retrieve service metadata using standardized
protocols such as WS-MetadataExchange and HTTP/GET requests. Both of these protocols are
supported by the MetadataExchangeClient type. You retrieve service metadata using the
System.ServiceModel.Description.MetadataExchangeClient type by providing an address for
the metadata endpoint and an optional binding. The binding used by a
System.ServiceModel.Description.MetadataExchangeClient instance can be one of the
default bindings from the MetadataExchangeBindings static class, a user-supplied binding, or a
binding loaded from an endpoint configuration for the IMetadataExchange contract. The
System.ServiceModel.Description.MetadataExchangeClient can also resolve HTTP URL
references to metadata using the HttpWebRequest type.
Resource Links for 70-513 WCF Certification Exam
27 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
By default, a System.ServiceModel.Description.MetadataExchangeClient instance is tied to a
single ChannelFactory instance. You can change or replace the
System.ServiceModel.ChannelFactory instance used by a
System.ServiceModel.Description.MetadataExchangeClient by overriding the
GetChannelFactory virtual method. Similarly, you can change or replace the HttpWebRequest
instance used by a System.ServiceModel.Description.MetadataExchangeClient to make
HTTP/GET requests by overriding the
System.ServiceModel.Description.MetadataExchangeClient.GetWebRequest(System.Uri,System
.String,System.String) virtual method.
In This Section
How to: Use Svcutil.exe to Download Metadata Documents
Demonstrates how to use Svcutil.exe to download metadata documents.
How to: Use MetadataResolver to Obtain Binding Metadata Dynamically
Demonstrates how to use the System.ServiceModel.Description.MetadataResolver to obtain
binding metadata dynamically at runtime.
How to: Use MetadataExchangeClient to Retrieve Metadata
Demonstrates how to use the System.ServiceModel.Description.MetadataExchangeClient
class to download metadata files into a System.ServiceModel.Description.MetadataSet object
that contains System.ServiceModel.Description.MetadataSection objects to write to files or for
other uses.
Using Metadata
Service metadata contains a machine-readable description of the service. Service metadata
includes descriptions of the service endpoints, bindings, contracts, operations, and messages.
You can use service metadata for a variety of purposes, including automatically generating a
client for consuming the service, implementing the service description, and dynamically
updating the binding for a client.
In This Section
Understanding Generated Client Code
Describes the different classes and interfaces the Svcutil.exe tool generates.
Resource Links for 70-513 WCF Certification Exam
28 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
How to: Retrieve Metadata and Implement a Compliant Service
Demonstrates how to retrieve metadata using Svcutil.exe and implement a compliant service.
Generating a WCF Client from Service Metadata
Demonstrates how to retrieve metadata using Svcutil.exe and generate a Windows
Communication Foundation (WCF) client.
Security Considerations with Metadata
When using the metadata features in Windows Communication Foundation (WCF), consider the
security implications of publishing, retrieving, and using service metadata.
When to Publish Metadata
WCF services do not publish metadata by default. To publish metadata for a WCF service you
must explicitly enable metadata publishing by adding metadata endpoints to your service (see
Publishing Metadata). Leaving metadata publishing disabled reduces the attack surface for your
service and lowers the risk of unintentional information disclosure. Not all services must publish
metadata. If you do not have to publish metadata, consider leaving it turned off. Note that you
can still generate metadata and client code directly from your service assemblies using the
ServiceModel Metadata Utility Tool (Svcutil.exe). For more information about using Svcutil.exe
to export metadata, see How to: Use Svcutil.exe to Export Metadata from Compiled Service
Code.
Publishing Metadata Using a Secure Binding
The default metadata bindings that WCF provides are not secure and they allow anonymous
access to the metadata. The service metadata that a WCF service publishes contains a detailed
description about the service and may intentionally or unintentionally contain sensitive
information. For example, service metadata may contain information about infrastructure
operations that was not intended to be broadcast publicly. To protect service metadata from
unauthorized access, you can use a secure binding for your metadata endpoint. Metadata
endpoints respond to HTTP/GET requests that can use Secure Sockets Layer (SSL) to secure the
metadata. For more information, see How to: Secure Metadata Endpoints.Securing your
metadata endpoints also provides a way for requesters to securely retrieve service metadata
without the risk of tampering or spoofing.
Resource Links for 70-513 WCF Certification Exam
29 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Using Only Trusted Metadata
You can use service metadata to automatically construct the run-time components required to
call the service. You can also use metadata at design time to develop a client application or at
runtime to dynamically update the binding a client uses to call a service. Service metadata can be
tampered with or spoofed when retrieved in an insecure manner. Tampered metadata can redirect
your client to a malicious service, contain compromised security settings, or contain malicious
XML structures. Metadata documents can be large and are frequently saved to the file system.
To protect against tampering and spoofing, use a secure binding to request service metadata
when one is available.
Using Safe Techniques for Processing Metadata
Service metadata is frequently retrieved from a service over a network using standardized
protocols such as WS-MetadataExchange (MEX). Many metadata formats include referencing
mechanisms for pointing to additional metadata. The MetadataExchangeClient type
automatically processes references for you in Web Services Description Language (WSDL)
documents, XML Schema, and MEX documents. The size of the MetadataSet object created
from the retrieved metadata is directly proportional to the MaximumResolvedReferences value
for the MetadataExchangeClient instance that is used and the MaxReceivedMessageSize value
for the binding being used by that MetadataExchangeClient instance. Set these quotas to
appropriate values as dictated by your scenario.
In WCF, service metadata is processed as XML. When processing XML documents, applications
should protect themselves against malicious XML structures. Use the XmlDictionaryReader
with appropriate quotas when processing XML and also set the ProhibitDtd property on the
XmlReaderSettings object for your XmlReader instance to true.The metadata system in WCF is
extensible and metadata extensions can be registered in your application configuration file (see
Extending the Metadata System). Metadata extensions can run arbitrary code, so you should
protect your application configuration file with appropriate access control lists (ACLs) and
register only trusted metadata extension implementations.
Validating Generated Clients
Resource Links for 70-513 WCF Certification Exam
30 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
When generating client code from metadata retrieved from a source that is not trusted, validate
the generated client code to ensure that the generated client conforms to your client applications
security policies. You can use a validating behavior to check settings on your client binding or
visually inspect code generated by tools. For an example of how to implement a client that
validates behaviors, see Client Validation.
Protecting Application Configuration Files
A service's application configuration file may control how and if metadata is published. It is a
good idea to protect the application configuration file with appropriate access control lists
(ACLs) to ensure an attacker cannot modify such settings.
Serialization and Deserialization
Windows Communication Foundation (WCF) includes a new serialization engine, the
DataContractSerializer. The DataContractSerializer translates between .NET Framework
objects and XML, in both directions. This topic explains how the serializer works.
When serializing .NET Framework objects, the serializer understands a variety of serialization
programming models, including the new data contract model. For a full list of supported types,
see Types Supported by the Data Contract Serializer. For an introduction to data contracts, see
Using Data Contracts. When deserializing XML, the serializer uses the XmlReader and
XmlWriter classes. It also supports the XmlDictionaryReader and XmlDictionaryWriter classes
to enable it to produce optimized XML in some cases, such as when using the WCF binary XML
format.WCF also includes a companion serializer, the NetDataContractSerializer. The
NetDataContractSerializer is similar to the BinaryFormatter and SoapFormatter serializers
because it also emits .NET Framework type names as part of the serialized data. It is used when
the same types are shared on the serializing and the deserializing ends. Both the
DataContractSerializer and the NetDataContractSerializer derive from a common base class,
the XmlObjectSerializer.
Caution:
The DataContractSerializer serializes strings containing control characters with a hexadecimal value
below 20 as XML entities. This may cause a problem with a non-WCF client went sending such data to a
WCF service.
Resource Links for 70-513 WCF Certification Exam
31 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Creating a DataContractSerializer Instance
Constructing an instance of the DataContractSerializer is an important step. After construction,
you cannot change any of the settings.
Specifying the Root Type
The root type is the type of which instances are serialized or deserialized. The
DataContractSerializer has many constructor overloads, but, at a minimum, a root type must be
supplied using the type parameter. A serializer created for a certain root type cannot be used to
serialize (or deserialize) another type, unless the type is derived from the root type. The
following example shows two classes.
C#
VB
[DataContract]
publicclass Person
{
// Code not shown.
}
[DataContract]
publicclass PurchaseOrder
{
// Code not shown.
}
This code constructs an instance of the DataContractSerializer that can be used only to
serialize or deserialize instances of the Person class.
C#
DataContractSerializer dcs = new DataContractSerializer(typeof(Person));
//This can now be used to serialize/deserialize Person but not PurchaseOrder.
Specifying Known Types
If polymorphism is involved in the types being serialized that is not already handled using the
KnownTypeAttribute attribute or some other mechanism, a list of possible known types must be
passed to the serializers constructor using the knownTypes parameter. For more information
about known types, see Data Contract Known Types.
Resource Links for 70-513 WCF Certification Exam
32 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
The following example shows a class, LibraryPatron, that includes a collection of a specific type,
the LibraryItem. The second class defines the LibraryItem type. The third and four classes (Book and
Newspaper) inherit from the LibraryItem class.
VB
_
PublicClass LibraryPatron
_
Public borrowedItems() As LibraryItem
EndClass
_
PublicClass LibraryItem
'code not shown
EndClass'LibraryItem
_
PublicClass Book
Inherits LibraryItem
'code not shown
EndClass
_
PublicClass Newspaper
Inherits LibraryItem
'code not shown
EndClass
The following code constructs an instance of the serializer using the knownTypes parameter.
C#
//Create a serializer for the inherited types using the knownType parameter.
Type[] knownTypes = new Type[] { typeof(Book), typeof(Newspaper) };
DataContractSerializer dcs =new DataContractSerializer(typeof(LibraryPatron), knownTypes);
// All types are known after construction.
Specifying the Default Root Name and Namespace
Normally, when an object is serialized, the default name and namespace of the outermost XML
element are determined according to the data contract name and namespace. The names of all
inner elements are determined from data member names, and their namespace is the data
Resource Links for 70-513 WCF Certification Exam
33 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
contracts namespace. The following example sets Name and Namespace values in the constructors
of the DataContractAttribute and DataMemberAttribute classes.
C#
[DataContract(Name = "PersonContract", Namespace = "http://schemas.contoso.com")]
publicclass Person2
{
[DataMember(Name = "AddressMember")]
public Address theAddress;
}
[DataContract(Name = "AddressContract", Namespace = "http://schemas.contoso.com")]
publicclass Address
{
[DataMember(Name = "StreetMember")]
publicstring street;
}
Serializing an instance of the Person class produces XML similar to the following.
123 Main Street
However, you can customize the default name and namespace of the root element by passing the
values of the rootName and rootNamespace parameters to the DataContractSerializer
constructor. Note that the rootNamespace does not affect the namespace of the contained
elements that correspond to data members. It affects only the namespace of the outermost
element.These values can be passed as strings or instances of the XmlDictionaryString class to
allow for their optimization using the binary XML format.
Setting the Maximum Objects Quota
Some DataContractSerializer constructor overloads have a maxItemsInObjectGraph parameter.
This parameter determines the maximum number of objects the serializer serializes or
deserializes in a single ReadObject method call. (The method always reads one root object, but
this object may have other objects in its data members. Those objects may have other objects,
and so on.) The default is 65536. Note that when serializing or deserializing arrays, every array
Resource Links for 70-513 WCF Certification Exam
34 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
entry counts as a separate object. Also, note that some objects may have a large memory
representation, and so this quota alone may not be sufficient to prevent a denial of service attack.
For more information, see Security Considerations for Data. If you need to increase this quota
beyond the default value, it is important to do so both on the sending (serializing) and receiving
(deserializing) sides because it applies to both when reading and writing data.
Round Trips
A round trip occurs when an object is deserialized and re-serialized in one operation. Thus, it
goes from XML to an object instance, and back again into an XML stream.Some
DataContractSerializer constructor overloads have an ignoreExtensionDataObject parameter,
which is set to false by default. In this default mode, data can be sent on a round trip from a
newer version of a data contract through an older version and back to the newer version without
loss, as long as the data contract implements the IExtensibleDataObject interface. For example,
suppose version 1 of the Person data contract contains the Name and PhoneNumber data members,
and version 2 adds a Nickname member. If IExtensibleDataObject is implemented, when sending
information from version 2 to version 1, the Nickname data is stored, and then re-emitted when the
data is serialized again; therefore, no data is lost in the round trip. For more information, see
Forward-Compatible Data Contracts and Data Contract Versioning.
Security and Schema Validity Concerns with Round Trips
Round trips may have security implications. For example, deserializing and storing large
amounts of extraneous data may be a security risk. There may be security concerns about re-
emitting this data that there is no way to verify, especially if digital signatures are involved. For
example, in the previous scenario, the version 1 endpoint could be signing a Nickname value that
contains malicious data. Finally, there may be schema validity concerns: an endpoint may want
to always emit data that strictly adheres to its stated contract and not any extra values. In the
previous example, the version 1 endpoints contract says that it emits only Name and PhoneNumber,
and if schema validation is being used, emitting the extra Nickname value causes validation to fail.
Enabling and Disabling Round Trips
To turn off round trips, do not implement the IExtensibleDataObject interface. If you have no
control over the types, set the ignoreExtensionDataObject parameter to true to achieve the same
effect.
Resource Links for 70-513 WCF Certification Exam
35 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Object Graph Preservation
Normally, the serializer does not care about object identity, as in the following code.
C#
[DataContract]
publicclass PurchaseOrder
{
[DataMember]
public Address billTo;
[DataMember]
public Address shipTo;
}
[DataContract]
publicclass Address
{
[DataMember]
publicstring street;
}
The following code creates a purchase order.
C#
//Construct a purchase order:
Address adr = new Address();
adr.street = "123 Main St.";
PurchaseOrder po = new PurchaseOrder();
po.billTo = adr;
po.shipTo = adr;
Notice that billTo and shipTo fields are set to the same object instance. However, the generated
XML duplicates the information duplicated, and looks similar to the following XML.
123 Main St.
123 Main St.
However, this approach has the following characteristics, which may be undesirable:
Performance. Replicating data is inefficient.
Resource Links for 70-513 WCF Certification Exam
36 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Circular references. If objects refer to themselves, even through other objects, serializing by replication
results in an infinite loop. (The serializer throws a SerializationException if this happens.)
Semantics. Sometimes it is important to preserve the fact that two references are to the same object, and
not to two identical objects.
For these reasons, some DataContractSerializer constructor overloads have a
preserveObjectReferences parameter (the default is false). When this parameter is set to true, a
special method of encoding object references, which only WCF understands, is used. When set
to true, the XML code example now resembles the following.
123 Main St.
The "ser" namespace refers to the standard serialization namespace,
http://schemas.microsoft.com/2003/10/Serialization/. Each piece of data is serialized only once
and given an ID number, and subsequent uses result in a reference to the already serialized data.
Note:
If both "id" and "ref" attributes are present in the data contract XMLElement, then the "ref" attribute is
honored and the "id" attribute is ignored.
It is important to understand the limitations of this mode:
The XML the DataContractSerializer produces with preserveObjectReferences set to true is not
interoperable with any other technologies, and can be accessed only by another DataContractSerializer
instance, also with preserveObjectReferences set to true.
There is no metadata (schema) support for this feature. The schema that is produced is valid only for the
case when preserveObjectReferences is set to false.
This feature may cause the serialization and deserialization process to run slower. Although data does not
have to be replicated, extra object comparisons must be performed in this mode.
Caution:
When the preserveObjectReferences mode is enabled, it is especially important to set the
maxItemsInObjectGraph value to the correct quota. Due to the way arrays are handled in this mode, it is
easy for an attacker to construct a small malicious message that results in large memory consumption
limited only by the maxItemsInObjectGraph quota.
Specifying a Data Contract Surrogate
Resource Links for 70-513 WCF Certification Exam
37 http://msdn.microsoft.com/en-us/library/ms123401.aspx http://www.jamesjfoster.com/blog/2010/resource-links-for-70-513-wcf-certification-exam/
Some DataContractSerializer constructor overloads have a dataContractSurrogate parameter,
which may be set to null. Otherwise, you can use it to specify a data contract surrogate, which
is a type that implements the IDataContractSurrogate interface. You can then use the interface to
customize the serialization and deserialization process. For more information, see Data Contract
Surrogates.
Serialization
The following information applies to any class that inherits from the XmlObjectSerializer,
including the DataContractSerializer and NetDataContractSerializer classes.
Simple Serialization
The most basic way to serialize an object is to pass it to the WriteObject method. There are three
overloads, one each for writing to a Stream, an XmlWriter, or an XmlDictionaryWriter. With
the Stream overload, the output is XML in the UTF-8 encoding. With the
XmlDictionaryWriter overload, the serializer optimizes its output for binary XML.
When u