Learning WCF Chapter2 Data Contracts

A data contract describes how CLR types map to XSD schema definitions.
Data contracts are the preferred way to enable serialization of complex types included in operation signatures as parameters or return values.
You create a data contract by applying the DataContractAttribute to a type.
To include members in serialization,you decorate them with the DataMemberAttribute;
this is an opt-in process that has nothing to do with visibility of members (public,protected,private).
By default,serialization is handled by the DataContractSerializer,a new serializer for WCF that succeeds the XmlSerializer used for earlier technologies such as ASMX.

In this section,you will become acquainted with the key features of data contracts and common serialization practices, including the following:
• How to apply data contract attributes to exercise control over type serialization
• Version tolerance and data contract versioning techniques
• Implementing IExtensibleDataObject to support version tolerance
• How to work with polymorphic types in the service contract
• How enumerations, arrays, and collections are serialized

First you’ll complete a lab that illustrates many of these scenarios,and then I’ll explain the related attributes and features in greater detail.

Lab: Working with Data Contracts

For this lab you will modify a preexisting type,turning it into a data contract so that it can be included in the service contract.
Using the DataContractAttribute and the DataMemberAttribute,you will control type serialization through the DataContractSerializer.
You’ll also test data contract version tolerance and implement the IExtensibleData interface in support of versioning.

Creating a data contract
In this part of the lab,you’ll turn a complex type into a data contract so that it can be included in a service contract,
and then take a look at the XSD schema produced for the type in the WSDL document.

1. Open the startup solution for this lab: <YourLearningWCFPath>\Labs\Chapter2\DataContracts\DataContracts.sln.
This solution includes the following projects:
ContentTypes
A class library that contains a LinkItem type used by the service.
LinkItem is a custom type that holds a title,description,URL and other details that can be associated with events,articles,photos,files,and so forth.
In this example, LinkItem is used to hold information about a gig (or event) for a band.
GigManager
A class library containing the service contract and service type.
The service contract exposes operations to save a LinkItem,and retrieve the saved LinkItem.
This example uses session to save the item.
See Chapter 5 for more on sessions.
Host
A console application for hosting the service.
GigEntry
A Windows client application that presents an interface for users to create and save a gig entry and retrieve the saved entry.

2. Try to run the solution at first.
From Visual Studio,press F5 to run the Host and the GigEntry client application.
An InvalidDataContractException will be thrown when the ServiceHost attempts to initialize.                     //这个地方是瞎扯,默认不会抛出异常的 ,虽然我用的是.net 3.0,也不会抛出异常
The error message indicates that the type ContentTypes.LinkItem cannot be serialized.

  [ServiceContract(Name = "GigManagerServiceContract", Namespace = "http://www.thatindigogirl.com/samples/2006/06", SessionMode = SessionMode.Required)]
    public interface IGigManagerService
    {
        [OperationContract]
        void SaveGig(LinkItem item);

        [OperationContract]
        LinkItem GetGig();
    }

3. Review the service contract for the solution.
Go to the GigManager project and open GigManagerService.cs.
The service contract is shown in Example 2-13.
The ContentTypes.LinkItem type is included in both operation signatures.

2. Try to run the solution at first.
From Visual Studio,press F5 to run the Host and the GigEntry client application.
An InvalidDataContractException will be thrown when the ServiceHost attempts to initialize.
The error message indicates that the type ContentTypes.LinkItem cannot be serialized.

3. Review the service contract for the solution.
Go to the GigManager project and open GigManagerService.cs.
The service contract is shown in Example 2-13.
The ContentTypes.LinkItem type is included in both operation signatures.

Example 2-13. IGigManagerService service contract
[ServiceContract(Name = "GigManagerServiceContract",
Namespace = "http://www.thatindigogirl.com/samples/2006/06",
SessionMode = SessionMode.Required)]
public interface IGigManagerService
{
[OperationContract]
void SaveGig(LinkItem item);
[OperationContract]
LinkItem GetGig( );
}

4. You are going to modify the LinkItem type to make it a valid data contract that can be included in the service contract.
Go to the ContentTypes project and add a reference to the System.Runtime.Serialization assembly.
Next,open LinkItem.cs and apply the DataContractAttribute to the class definition,
and apply the DataMemberAttribute to each private field so that they are included in the serialized type definition.
Add a using statement for System.Runtime.Serialization as well.
The resulting type should appear as shown in Example 2-14.

5. Compile the solution and attempt to run the host once again.
This time you won’t see an exception because LinkItem is now a data contract.

6. View the service description in the browser;
you want to see the XSD schema representation of the LinkItem data contract.
Browse to the following address:http://localhost:8000 and click the ?wsdl link to navigate to the service description.
This will generate the service description so that you can browse to the following address: http://localhost:8000/?xsd=xsd2.
You should see a schema like the one shown in Example 2-15.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.datacontract.org/2004/07/ContentTypes" elementFormDefault="qualified" targetNamespace="http://schemas.datacontract.org/2004/07/ContentTypes">
<xs:complexType name="LinkItem">
<xs:sequence>
<xs:element minOccurs="0" name="DateEnd" type="xs:dateTime"/>
<xs:element minOccurs="0" name="DateStart" type="xs:dateTime"/>
<xs:element minOccurs="0" name="Description" nillable="true" type="xs:string"/>
<xs:element minOccurs="0" name="ID" type="xs:long"/>
<xs:element minOccurs="0" name="Title" nillable="true" type="xs:string"/>
<xs:element minOccurs="0" name="Url" nillable="true" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="LinkItem" nillable="true" type="tns:LinkItem"/>
</xs:schema>

Notice that the naming convention for each data member matches the field name in the type definition.
In addition,the order of each element in the schema sequence is alphabetical,
as opposed to the order of appearance in the type definition.
Another thing to note is that the namespace for the type does not match the service contract target namespace;
instead,it uses the domain shemas.datacontract.org.

Note:

Other .NET serialization techniques are dependent on the reflection order of types.
This can introduce problems when developers inadvertently reorder the class definition,not realizing it can cause incompatibilities.

时间: 2024-08-06 05:09:07

Learning WCF Chapter2 Data Contracts的相关文章

Learning WCF Chapter2 Service Contracts

A service contract describes the operations supported by a service,the message exchange pattern they use,and the format of each message. The service contract is also the main driver for generating a service description. A valid WCF service implements

Learning WCF Chapter2 WCF Contracts and Serialization

So far I’ve talked about the standards behind it all,but in fact WCF hides most of this from the developer by providing a programming interface for designing service contracts and controlling the message format. Application messaging requirementsare

Learning WCF Chapter2 Service Description

While messaging protocols are responsible for message serialization formats,there must be a way to capture the protocols required to communicate between clients and services. In Chapter 1,you worked with WSDL documents,which describe the requirements

Learning WCF Chapter2 Messaging Protocols

In Chapter 1,you were introduced to fundamental WCF concepts,      在章节1中,学习了wcf中的基础概念including how to create and consume a service,           包括如何创建以及调用服务how to host a service and expose endpoints where it can be reached by clients,    如何托管服务,使得客户端可以

Learning WCF Chapter1 Generating a Service and Client Proxy

In the previous lab,you created a service and client from scratch without leveraging the tools available to WCF developers. Although this helps you to understand the raw requirements for sending messages between clients and services,in reality,develo

R8:Learning paths for Data Science[continuous updating…]

Comprehensive learning path – Data Science in Python Journey from a Python noob to a Kaggler on Python So, you want to become a data scientist or may be you are already one and want to expand your tool repository. You have landed at the right place.

In machine learning, is more data always better than better algorithms?

In machine learning, is more data always better than better algorithms? No. There are times when more data helps, there are times when it doesn't. Probably one of the most famous quotes defending the power of data is that of Google's Research Directo

Matterport3D: Learning from RGB-D Data in Indoor Environments

Abstract Access to large, diverse RGB-D datasets is critical for training RGB-D scene understanding algorithms. However, existing datasets still cover only a limited number of views or a restricted scale of spaces. In this paper, we introduce Matterp

好文章之AI系列(—)——Deep learning with synthetic data

Deep learning with synthetic data will make AI accessible to the masses https://towardsdatascience.com/deep-learning-with-synthetic-data-will-make-ai-accessible-to-the-masses-15b99343dd0e 原文地址:https://www.cnblogs.com/carsonzhu/p/10268770.html