Tải bản đầy đủ (.pdf) (393 trang)

Tài liệu The C# Programming Language, Third Edition doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (14.85 MB, 393 trang )

®

MICROSOFT .NET
DEVELOPER
SAMPLE CHAPTERS

informit.com/teched09

Sampler1_cover.indd 1

4/29/09 1:12:02 PM


MICROSOFT ® .NET
DEVELOPER
eBOOK TABLE OF CONTENTS
The C# Programming Language,
Third Edition

Effective REST Services via .NET
9780321613257

Kenn Scribner, Scott Seely
CHAPTER 3: Desktop Client
Operations

9780321562999

Essential LINQ
9780321564160


Framework Design Guidelines,
Second Edition

Charlie Calvert, Dinesh Kulkarni

97800321545619

CHAPTER 3: The Essence of
LINQ

Krzysztof Cwalina, Brad Abrams
CHAPTER 3: Naming Guidelines

Anders Hejlsberg, Mads Torgersen,
Scott Wiltamuth, Peter Golde
CHAPTER 3: Basic Concepts

Visual Studio Tools for
Office 2007

Essential Silverlight 3

9780321533210

Ashraf Michail
CHAPTER 3: Graphics

9780321554161

Eric Carter, Eric Lippert

CHAPTER 3: Programming Excel

Concurrent Programming
on Windows

Essential C# 3.0: For .NET
Framework 3.5, Second Edition

9780321434821

9780321533920

Joe Duffy
CHAPTER 3: Threads

Mark Michaelis
CHAPTER 3: Operators and
Control Flow
Advanced ASP.NET AJAX Server
Controls for .NET Framework 3.5
9780321514448

Adam Calderon, Joel Rumerman
CHAPTER 3: Components

Google
Bookmarks

TOC_copyright.indd Sec1:1


Delicious

Digg

Facebook

StumbleUpon

Reddit

Twitter

4/29/09 1:14:01 PM


Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a
trademark claim, the designations have been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed
or implied warranty of any kind and assume no responsibility for errors or omissions. No liability
is assumed for incidental or consequential damages in connection with or arising out of the use of
the information or programs contained herein.
Copyright © 2009 by Pearson Education, Inc.

BROUGHT TO YOU BY

UPPER SADDLE RIVER, NJ | BOSTON | INDIANAPOLIS | SAN FRANCISCO | NEW YORK | TORONTO | MONTREAL | LONDON | MUNICH
PARIS | MADRID | CAPETOWN | SYDNEY | TOKYO | SINGAPORE | MEXICO CITY

TOC_copyright.indd Sec1:2


4/21/09 10:13:14 AM


Google
Bookmarks

Chapter Openers_Sampler1.indd 1

Delicious

Digg

Facebook

StumbleUpon

Reddit

Twitter

4/20/09 2:44:07 PM


Ken Scribner
Scott Seely

Effective REST Services via .NET
For .NET Framework 3.5
Developers are rapidly discovering the power of REST to simplify the development of

even the most sophisticated Web services–and today’s .NET platform is packed with
tools for effective REST development. Now, for the first time, there’s a complete, practical
guide to building REST-based services with .NET development technologies.
Long-time .NET and Web services developers and authors Kenn Scribner and Scott
Seely explain why REST fits so smoothly into the Internet ecosystem, why RESTful
services are so much easier to build, what it means to be RESTful, and how to identify
behaviors that are not RESTful. Next, they review the core Internet standards and .NET
technologies used to develop RESTful solutions and show exactly how to apply them on
both the client and server side. Using detailed
code examples, Scribner and Seely begin with simple ASP.NET techniques, and then
introduce increasingly powerful options–including Windows Communication
Foundation (WCF) and Microsoft’s cloud computing initiative, Azure. Coverage includes
• Accessing RESTful services from desktop applications, using Windows Forms and
WPF
• Supporting Web client operations using Silverlight 2.0, JavaScript, and other
technologies
• Understanding how IIS 7.0 processes HTTP requests and using that knowledge to
build better REST services
• Constructing REST services based on traditional ASP.NET constructs
• Utilizing the ASP.NET MVC Framework to implement RESTful services more
effectively
• Taking advantage of WCF 3.5’s powerful REST-specific capabilities
• Creating RESTful data views effortlessly with ADO.NET Data Services
• Leveraging Microsoft’s Azure cloud-computing platform to build innovative new
services

AVAILABLE
• BOOK: 9780321613257
• SAFARI ONLINE
• KINDLE: ????????????


About the Authors
Kenn Scribner has been writing
cutting-edge, software-based books on
Microsoft technologies for more than
10 years. His books include Windows
Workflow Foundation Step by Step
(Microsoft Press) and Understanding
SOAP (SAMS). Kenn is a senior software
consultant whose clients have included
The Weather Channel, CBS, Burton, and
Microsoft.
Scott Seely, an architect at MySpace,
works on the OpenSocial API, one of
the world’s most successful REST-based
APIs. Before joining MySpace, he was a
developer on the Windows Communication Foundation team at Microsoft. His
books include Creating and Consuming
Web Services in Visual Basic (AddisonWesley) and SOAP: Cross Platform
Web Service Development Using XML
(Prentice Hall).

• Choosing the right .NET technology for each REST application or service

informit.com/aw

Chapter Openers_Sampler1.indd 2

4/20/09 2:44:11 PM



03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 87

3
Desktop Client Operations

are made available on private intranets
and the Internet at large. .NET has many different tools that allow you
to consume these services from any application environment: Web, desktop, and mobile. In this chapter, we will examine the classes and tools you
need to use in order to build applications for both of the .NET desktop class
libraries: Windows Forms (WinForms) and Windows Presentation Foundation (WPF).

E

V E RY D AY, M O R E R E S O U R C E S

We Still Write Desktop Applications
The desktop application has all sorts of benefits that, today, trump anything
you can do on the Web. Desktop applications have access to storage
devices, arbitrary network resources, and network hardware. They can
make application demands that their Web brethren cannot. For example,
you can write a desktop application that will install only to a Windows
machine that has .NET 3.5 or greater installed. Finally, these applications
can do something useful even when they are disconnected from the network. Outlook will still let you read e-mail and create new messages when

you are disconnected from your Exchange server. Outlook’s fraternal twin,
Outlook Web Access, needs a network connection to work. Because of the
capability to do so much more when having access to inexpensive yet

3


03_0321613252_ch03.qxd

4

3/25/09

11:32 AM

Page 88

Chapter 3: De sktop Client Operations

powerful hardware resources (memory, CPU, storage, and so forth), desktop applications are not going away any time soon.
These desktop applications frequently become more useful, however,
when they can connect to network-based resources. E-mail can be sent and
received. Games get updates, communicate high scores, and, most important, allow for players to meet and play interactively. Individuals at your
company update, modify, and delete documents through WebDAV and
Windows Explorer. As a desktop application developer, you have one question you have to answer: “How do I get that data?” This chapter shows you
how to obtain information from RESTful services.
Everything in this chapter can be applied to any executable you
might write. Accessing RESTful data does not change whether you use a
command-line application, a Windows service, a Windows Forms (WinForms) application, or even a Windows Presentation Foundation (WPF)
application. The chapter concentrates on applications created using WinForms and WPF because those two environments have a requirement you

do not necessarily have in other environments. Such as? The user interface
(UI) has to stay responsive while the Web request is executing.

An Introduction to our Web Service
This chapter and the next focus on consuming RESTful services. The later
parts of this book focus on implementing RESTful architectures. In Chapter
8, “Building REST Services Using WCF,” we talk about building RESTful
services using Windows Communication Foundation (WCF). This chapter
utilizes one of the WCF services from Chapter 8. At this point, you do not
need to know how the service is built, but you do need to know what the
service does. A copy of the service is provided in this chapter’s sample project in order to keep things easier to build and navigate as you work with
this chapter’s sample client applications.
The service itself demonstrates a few basic capabilities that pretty much
every consumer/producer needs to understand:
• Exchanging binary data
• Exchanging simple data types


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 89

An Introduction to our Web Ser vice

• Exchanging structured data
• Exchanging arrays of structured data

Understanding these simple building blocks enables you to build or
consume any RESTful service. When I was looking at scenarios that demonstrate the previous capabilities without needing to implement an overly
sophisticated solution, one scenario popped out as simple to understand
and small enough to fit within the chapter of a book: sharing photos. Photos
are binary and have extra, interesting attributes, such as an owner and a
caption. In our case, photos have these pieces of metadata:
• Is the photo public or private?
• Who is the photo owner?
• Does the photo have a caption, and if so, what is it?
• Does the photo have an extended description?
• What is the photo’s unique identifier?
The REST service allows users to do all sorts of things with photos. For
photos you own, you can update the caption and description, and state
whether the photo is public. Regardless of who you are, you can ask for a
list of photos from a particular user. If you are that user, the list contains all
photos. If you ask for someone else’s list, only public photos are returned.
To do all this work, the service supports URLs of the following forms:
• Add an image:

to [base service address]/AddImage

• Update an image:
• Delete an image:
• Get images for a user:
{username}

to [base service address]/Image/{imageId}
to [base service address]/Image/{imageId}
to [base service address]/Images/


• Get a single image for a user:
{imageId}

to [base service address]/Image/

For this chapter, we will be using the XML-based endpoint for this serv,
, and
verbs all manipulate an
, which in
ice. The
serialized XML form appears as shown in Listing 3.1.

5


03_0321613252_ch03.qxd

6

3/25/09

11:32 AM

Page 90

Chapter 3: De sktop Client Operations
Listing 3.1:

serialized as XML


Chapter 4, “Web Client Operations,” shows the same object in JavaScript
Object Notation (JSON) format. Just to show the difference here, the JSON
representation of the object is given in Listing 3.2.
Listing 3.2:

serialized as JSON

It’s important to note that the only time
will contain data is
request. The only time that
will be populated
for an HTTP
request. (You’d use the URI contained within
is in response to an HTTP
to request the actual image.) Lastly, the RESTful service validates
users based on a username and password.

Reading Data
We have lots of options for dealing with XML markup. Because reading and
writing data is a big part, maybe even the biggest part, of consuming RESTful services, the first code examples in this chapter detail how we would
as XML. A complete description of every possible mechread the
anism to read and write data is far beyond the scope of this book. Instead,


03_0321613252_ch03.qxd

3/25/09

11:32 AM


Page 91

Reading Data

this section introduces you to the .NET namespaces and tools most often
used—those you need to be familiar with. With knowledge of the basics,
you should be able to implement special cases and go as deep as you need
to go. As a goal, we want to read the XML and transform it into an object
that is more useful to a .NET developer, a process known as deserialization.
Let’s start with an object that can hold the data, which I’ve named
.
needs seven fields: one for each element in the XML
representation shown in Listing 3.1. Given the XML from Listing 3.1, the
class should have the structure shown in Listing 3.3.
Listing 3.3: The

class

NOTE
Something to keep in mind is that you do not always need to populate
a class to make use of the data. You could keep the data in an XML document, a database, or another storage medium. Populating the
class is simply for the convenience of the application’s C#based code. Populating a form, placing data in a database, or something else are also possible goals that similarly rely on the capability
to extract information from an XML stream.

With .NET, we have lots of options for dealing with XML markup. We
and
can parse the XML manually using
. We can also create special classes and use the serialization mechanisms offered by
and
.


7


03_0321613252_ch03.qxd

8

3/25/09

11:32 AM

Page 92

Chapter 3: De sktop Client Operations

To demonstrate the various techniques for working with XML data, I’ve
and placed it in
created a sample application called
this chapter’s demonstration solution. All the XML deserialization techniques just mentioned are illustrated using a static method that returns a
object, which is hard-coded as an XML string for simplicsingle
ity. The code offers access to the XML-based representation via a
named
, which is shown in Listing 3.4.
Listing 3.4: The preserialized

resource

The sample code demonstrates deserializing XML data using
,

, XML serialization, and data contract serialization, as well
. Each of these techas a modified technique I call
niques is executed using a simple loop that iterates a list of delegates, as
shown in Listing 3.5.
Listing 3.5:

method


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 93

Reading Data

has a long history with the .NET Framework—it has been part
, you load the
of the framework since the beginning. To use
document with XML that might come from a number of sources: a file, a
from
URL, a string, or a stream. You can also populate an
scratch using code, creating each element by hand.
instance, you would use its
To load XML data into an
to load an XML string or its
method to use XML data encoded

within one of the other sources (file, stream, and so on). After the document
is loaded, you can extract the data; a number of mechanisms exist to help
extract data to be placed in objects for code manipulation. An obvious
approach is to iterate over the contents of the document, looking for nodes
with known element names. Unfortunately, this technique can be fairly
code heavy. Another technique involves writing code that knows where the
element should be located within the document and then using indexers to
grab the text of that node. This technique winds up being very fragile
because the layout of the document might change over time. Adding or
deleting items from the document can cause specific indexes to change and
code to malfunction accordingly.
involves
My preferred technique to extract data from an
.
has a
using XPath expressions and
that accepts an XPath expression and an
method named
. XPath is a rich language for querying XML.
optional
The most common queries involve looking for elements or attributes
with known names. Each element and attribute in the XML has an XML

9


03_0321613252_ch03.qxd

10


3/25/09

11:32 AM

Page 94

Chapter 3: De sktop Client Operations

qualified name (QName). To choose a specific element or attribute, you need
to know the item’s QName. The QName is consistent no matter the XML
namespace being used.
has a namespace of shown in Listing 3.4 establishes the
Book/2008. The
default namespace with this markup:

This allows us to identify
content without any prefixes for our
convenience. The declaration could have just as easily been

If this was the case, the
XML would have to be changed to pre. The resulting XML, regardless of how
fix all element tags with
the namespace was declared, would be considered equivalent between the
two documents. What does this digression have to do with anything? Well,
if we want to ask for the caption, description, or other elements contained
within the XML document, we have to present a name that is meaningful
via the XPath expression. These prefixes do not have to match what is in the
actual XML document because XPath expressions operate against the
infoset representation of the document, not the string representation.


NOTE
One cannot talk about XML without talking about the infoset. In a nutshell, the infoset representation concentrates on the tree-based structure of the XML document rather than what data the tree structure
contains. Everything in an infoset is some type of XML node: attribute,
text, element, whitespace, comment, processing instruction, and so on.
Elements and attributes have QNames. Using this, specification
authors found it easier to write specifications because they were no
longer worrying about XML representation. Developers have since
used this to introduce new serialization schemes beyond XML 1.0
(text). Today, many binary serializers have been created to reduce the
bulkiness issues associated with XML.


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 95

Reading Data

To read more about infosets, consider going to the source specification
at www.w3.org/TR/xml-infoset/. O’Reilly also has a great site with
articles and information about XML in general at www.xml.com.

Knowing what we do about infosets, we need a crash course in XPath.
XPath expressions can get complicated. However, most queries are fairly
straightforward: Select all nodes with this name, select the first node with
this name, only select nodes at this location relative to the root, and so forth.

Here is some of the basic XPath syntax:


: Used at the start of an expression to select any node with a given
selects all nodes named .
name. Example:



: When used as a single character, denotes that the expression starts
selects all
at the node being queried. Example:
that are children of a node named
.
nodes named



: An element may contain a text node. The expression
allows the query to select the child text nodes. Example:
selects all text contents within nodes
.
named



: Elements may contain attribute tags. The syntax
says that the name that follows in the XPath expression is an attribute. Example: If we have XML such as
and the XPath expression
, then the result of the

.
expression is

XPath allows for other options too. You can perform logical tests such as
, , , , and more. You can also check for string contents and other things
to filter the results to a finer degree. The articles at xml.com provide a rich
source of information for how to handle most of these deeper issues.
For our example, we will want to parse all nodes with the following
QName:

11


03_0321613252_ch03.qxd

12

3/25/09

11:32 AM

Page 96

Chapter 3: De sktop Client Operations

To identify the prefix we will map to the namespace, we use a class
. By setting up the name correctly,
called
elements:
we can now ask for all


At this point, we can use additional XPath expressions to iteratively
to read the
select child nodes, or we can use a
approach
remaining data directly. The choice is up to you. The
has the benefit of being able to spin through the node data fairly quickly,
approach is
whereas the XPath approach is more deliberate. The
presented only for completeness because both approaches are useful. An
tends to require more testing effort as changes to document
structure can introduce bugs fairly easily, which is something to keep in
mind.
, we can then look at each element individually.
Using an
and
. The
repEach element has two name properties:
represents the simple
resents the QName for the element. The
form of the element tag name—essentially a non-namespace version. If
your expectation is that the names within a given node will not vary, and
. Otherthat name collisions will not occur, you can safely use
wise, if names in a node might be reused across XML namespaces (for
example, address could mean memory address or street address), use the
property instead. The
then has helper methods to read common data types: strings, numbers, and Boolean values. Using this knowl. The code I’ve
edge, we can now read the XML using an
, that
provided introduces a helper method,

advances the reader to the (child) text node. This particular function exists
to make sure that we don’t skip over other elements by advancing the
.
reader too far using functions like
will advance the reader to the next
node. A
, as in the
loop shown in Listing 3.6, would
call to
to slow it down.
march past too many elements without


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 97

Reading Data
Listing 3.6: Reading and consuming XML using

and XPath

continues

13



03_0321613252_ch03.qxd

14

3/25/09

11:32 AM

Page 98

Chapter 3: De sktop Client Operations
Listing 3.6: Continued

As you can see from Listing 3.6, that is an awful lot of code to translate
the XML into something readable. If this RESTful services thing is ever
going to take off, there needs to be a simpler solution. There is, and we will


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 99

Reading Data

get to it. For this very reason, we will be skipping how to serialize data back

out. If you are writing the object, you have more control and better options
than manipulating XML documents directly for most situations, so it
doesn’t make sense to even describe how that’s done here. We’ll save that
topic for later in the chapter when we look at the XML serializers.

If you are using .NET 3.5 or later, you have something truly wonderful at
your disposal. You have Language Integrated Query (LINQ). LINQ is
mostly syntactic sugar when represented in a .NET language like C# or
VB.NET. The actual generated code is very procedural. But, from a developer point of view, the expressions are declarative. Fortunately, the technology has been written about enough that it is unnecessary to promote its
use here. If you do any work with LINQ, you have to go out and buy the
by Joseph and Ben Albahari, ISBN 978-0-59651924-7, from O’Reilly. It’s a tiny 160-page book that will literally fit into the
back pocket of your jeans.
Within LINQ, there are all sorts of variants. LINQ to objects lets you execute nifty queries over collections. LINQ to SQL generates SQL queries.
And perhaps not surprisingly, LINQ to XML operates over XML documents. Specifically, LINQ to XML (XLINQ) operates on types known as
.
knows how to read and write
data types:
and
. As a result, you
using
code from the preceding section to do your parsing.
can use the
So we will skip that and move on to other concepts, like queries.
With XLINQ, we still need to think in terms of infosets. When we ask for
an element with a particular name, we ask for the element by QName. The
.
XLINQ type representing the QName is named
by concatenating a
with
You create an

for
a string representing the element name. To create the
and then create the appropriate
, use the following bit of
code:

15


03_0321613252_ch03.qxd

16

3/25/09

11:32 AM

Page 100

Chapter 3: De sktop Client Operations

Most of the types we deal with in LINQ are
types. In our
case, we will normally want only the first item in that list (and, in fact, the
XML document we’re working with contains only one element). .NET 3.5
called
that
implements an extension method for
provides this capability quite handily. Using all this basic knowledge, the
into an

becomes simpler. To select
code to parse the
of the target
a named node within the current node, you pass the
method. You can then select
node to the current node’s
of that item, as demonthe first element from that list and pick off the
strated in Listing 3.7.
Listing 3.7: Reading and consuming XML using

and XLINQ

The
code has some advantages over the
version. First and foremost, it is a lot shorter. Shorter code typically leads to
fewer bugs since most developers implement code with a consistent ratio


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 101

Reading Data

of bugs to lines of code. This ratio is not intentional—as humans we just
tend to make mistakes at a steady pace. An issue with the code in Listing 3.7

,
is that it has very little in the way of error handling. If the
,
, or
items fail to parse, the code fails for
and leave fields blank on
all items. If we would rather load the
failure, the code could be rewritten as shown in Listing 3.8 to provide for
deserialization failover.
Listing 3.8: Reading and consuming XML using

and XLINQ with failover

continues

17


03_0321613252_ch03.qxd

18

3/25/09

11:32 AM

Page 102

Chapter 3: De sktop Client Operations
Listing 3.8: Continued


Again, this all depends on whether you want things to fail whenever
bad input data is encountered. Most of the time, invalid data that appears
anywhere in the object implies that you do not want to continue deserializing that XML stream. When that is the case, the short version of this code
is completely appropriate. When failover is called for, however, you need
the extra code shown in Listing 3.8.

Wouldn’t it be great if you could just tell the runtime what your object
looked like and then it could figure out how to read the XML and populate
that object for you? As it happens, this is possible. To do this, we can go to
. In the
one of my favorite .NET namespaces:
.NET world, it is the king of XML reading and writing within the bits
shipped with the framework. It handles attributes, special serialization, and
schema generation. Most of this work is directed with simple attributes
placed on public classes, fields, and properties. And it implements the parts
of the XML Schema specification that map into .NET.


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 103

Reading Data

NOTE

As it happens, .NET doesn’t implement the full suite of schema constructs identified in the XML Schema specification. If you create a
schema using a tool outside of .NET, you could be asking for trouble
if you later try to incorporate those schemas into .NET code. For example, Altova has tools with XML Spy that implement all far corners of
the XML Schema Document specification and provide features not
found in .NET. If you need to support facets and other fancy features
of XSD, you need to go beyond what Microsoft ships with the framework. In practice, this kind of specialization is needed only for sophisticated XML processing in a small set of scenarios.

The most common attributes used in the
are listed here:


: Declares the XML element name and namespace for a given property when that property appears in an XSD or
XML document.



: Declares the XML attribute name and
namespace for a given property when that property appears in an
XSD or XML document.



: Declares the name and namespace for a given
class or enum within an XSD.



: Declares the name and namespace for a given
class or enum when that data type is used as the root of an XML
document.




: Declares the name of an enumeration value
when that enum appears in an XSD or XML document.



: Prevents serialization of this member. By
default, all public members are serialized.

19


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 104

Chapter 3: De sktop Client Operations

20



: Allows the developer to control the names used
when serializing arrays of items.




: Collaborates with
.
allows for a given collection to contain
more than one type of object.

This information is consumed by another class named
.
learns how to convert between XML and
.NET types by reading these attributes via reflection. The initial instance of
for a given type is expensive to build in terms of time,
an
so quite often an instance is created early and held for the duration of the
application’s lifetime. After you have the serializer in hand, however, you
can read XML into objects and write objects as XML into a stream or file
with a single method call.
class with the
Using this knowledge, we need to decorate the
right set of attributes to drastically reduce the amount of code we have to
write to eventually serialize and deserialize it. The class should be decoand all properties with
rated with an
. The code in Listing 3.9 demonstrates these attributes in action.
inforI could have written even less code by not filling in the
mation as the XML element name defaults to the property name, but I
wanted to demonstrate how you establish the tie between the property
name and the corresponding XML element. If you want to reduce the size
of the serialized XML stream, one way to do it is to provide very short XML
is the tool you’d use for this. We

element names, and
is of type
.
do run into one snag, though:
does not have a parameterless constructor, which is a requirement for
. Because of this,
cannot automatically read
values. There is a workaround: We create a new
propand write
. Within that property, we read and write the
erty,
for everyone else to use. It’s a small change to the class but results in simpler code overall than any mechanism seen so far.


03_0321613252_ch03.qxd

3/25/09

11:32 AM

Page 105

Reading Data
Listing 3.9:

with XML serialization attributes applied

With the data type decorated with all these different attributes, what
now? Happily, deserialization
code do we implement to read an

distills down to two lines of code:

21


03_0321613252_ch03.qxd

22

3/25/09

11:32 AM

Page 106

Chapter 3: De sktop Client Operations

As you can see, we are no longer parsing the XML ourselves. This means
that potential bugs in the code we write become less likely—less code
is that it handles
means fewer defects. The great thing about
elements being out of order, missing elements, and so on. There is one more
serialization mechanism that has an extra benefit if you can use this mechanism: blindingly fast speed. Let’s look at that topic next.

is part of a
family of serializers introduced with .NET 3.0 that all inherit from
. These serializers specialize in reading and writing objects to XML, JSON, and other formats. In general, these serializers read and write XML faster than anything else on the
,
.NET platform. When looking specifically at
however, understand that the speed comes at a price:

does not handle XML attributes and it does not handle arbitrarily
handles serialization of the folordered elements.
lowing types of data:
• Classes that implement
.
• Types marked with the

.

• Primitive types and enumerations. These types are implicitly serializable.
• Types marked with
.
• Undecorated objects. This feature, new in .NET 3.5 SP1, allows for
serializing objects that have no special attribution. In this case, only
types with public, default constructors can be serialized. The
will serialize only public fields and properties.
,
Like
model relies on attributes.

’s explicit serialization


×