码迷,mamicode.com
首页 > 其他好文 > 详细

Learning WCF Chapter2 Data Contracts

时间:2015-07-21 12:04:46      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:


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.

 

Learning WCF Chapter2 Data Contracts

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4663874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!