Effective REST Services via .NET9780321613257 Kenn Scribner, Scott Seely CHAPTER 3: Desktop Client Operations Essential LINQ 9780321564160 Charlie Calvert, Dinesh Kulkarni CHAPTER 3: Th
Trang 1MICROSOFT ® NET
DEVELOPER
SAMPLE CHAPTERS
informit.com/teched09
Trang 2Effective REST Services via NET
9780321613257 Kenn Scribner, Scott Seely CHAPTER 3: Desktop Client Operations
Essential LINQ
9780321564160 Charlie Calvert, Dinesh Kulkarni CHAPTER 3: The Essence of LINQ
Visual Studio Tools for Offi ce 2007
9780321533210 Eric Carter, Eric Lippert CHAPTER 3: Programming Excel
Concurrent Programming
on Windows
9780321434821 Joe Duffy CHAPTER 3: Threads
The C# Programming Language, Third Edition
9780321562999 Anders Hejlsberg, Mads Torgersen, Scott Wiltamuth, Peter Golde CHAPTER 3: Basic Concepts
Framework Design Guidelines, Second Edition
97800321545619 Krzysztof Cwalina, Brad Abrams CHAPTER 3: Naming Guidelines
Essential Silverlight 3
9780321554161 Ashraf Michail CHAPTER 3: Graphics
Essential C# 3.0: For NET Framework 3.5, Second Edition
9780321533920 Mark Michaelis CHAPTER 3: Operators and Control Flow
Google Bookmarks Delicious Digg Facebook StumbleUpon Reddit Twitter
DEVELOPER
eBOOK TABLE OF CONTENTS
Advanced ASP.NET AJAX Server Controls for NET Framework 3.5
9780321514448 Adam Calderon, Joel Rumerman CHAPTER 3: Components
Trang 3UPPER SADDLE RIVER, NJ | BOSTON | INDIANAPOLIS | SAN FRANCISCO | NEW YORK | TORONTO | MONTREAL | LONDON | MUNICH
PARIS | MADRID | CAPETOWN | SYDNEY | TOKYO | SINGAPORE | MEXICO CITY
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
Trang 4Bookmarks Delicious Digg Facebook StumbleUpon Reddit Twitter
Trang 5Developers 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 fi rst 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 fi ts 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-specifi c capabilities
• Creating RESTful data views effortlessly with ADO.NET Data Services
• Leveraging Microsoft’s Azure cloud-computing platform to build innovative new services
• Choosing the right NET technology for each REST application or service
Effective REST Services via NET
For NET Framework 3.5
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 Workfl ow 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 Communica- tion Foundation team at Microsoft His books include Creating and Consuming Web Services in Visual Basic (Addison- Wesley) and SOAP: Cross Platform Web Service Development Using XML (Prentice Hall).
Ken Scribner Scott Seely
Trang 6Desktop Client Operations
E V E RY D AY, M O R E R E S O U R C E Sare made available on private intranetsand the Internet at large .NET has many different tools that allow you
to consume these services from any application environment: Web, top, and mobile In this chapter, we will examine the classes and tools youneed to use in order to build applications for both of the NET desktop classlibraries: Windows Forms (WinForms) and Windows Presentation Foun-dation (WPF)
desk-We Still Write Desktop Applications
The desktop application has all sorts of benefits that, today, trump anythingyou can do on the Web Desktop applications have access to storagedevices, arbitrary network resources, and network hardware They canmake application demands that their Web brethren cannot For example,you can write a desktop application that will install only to a Windowsmachine that has NET 3.5 or greater installed Finally, these applicationscan do something useful even when they are disconnected from the net-work Outlook will still let you read e-mail and create new messages whenyou are disconnected from your Exchange server Outlook’s fraternal twin,Outlook Web Access, needs a network connection to work Because of thecapability to do so much more when having access to inexpensive yet
Trang 7powerful hardware resources (memory, CPU, storage, and so forth), top applications are not going away any time soon.
desk-These desktop applications frequently become more useful, however,when they can connect to network-based resources E-mail can be sent andreceived Games get updates, communicate high scores, and, most impor-tant, allow for players to meet and play interactively Individuals at yourcompany update, modify, and delete documents through WebDAV andWindows Explorer As a desktop application developer, you have one ques-tion you have to answer: “How do I get that data?” This chapter shows youhow to obtain information from RESTful services
Everything in this chapter can be applied to any executable youmight write Accessing RESTful data does not change whether you use acommand-line application, a Windows service, a Windows Forms (Win-Forms) application, or even a Windows Presentation Foundation (WPF)application The chapter concentrates on applications created using Win-Forms 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 laterparts of this book focus on implementing RESTful architectures In Chapter
8, “Building REST Services Using WCF,” we talk about building RESTfulservices using Windows Communication Foundation (WCF) This chapterutilizes one of the WCF services from Chapter 8 At this point, you do notneed to know how the service is built, but you do need to know what theservice does A copy of the service is provided in this chapter’s sample proj-ect in order to keep things easier to build and navigate as you work withthis chapter’s sample client applications
The service itself demonstrates a few basic capabilities that pretty muchevery consumer/producer needs to understand:
Chapter 3: Desktop Client Operations
4
Trang 8• Exchanging structured data
Understanding these simple building blocks enables you to build orconsume any RESTful service When I was looking at scenarios that demon-strate the previous capabilities without needing to implement an overlysophisticated solution, one scenario popped out as simple to understandand small enough to fit within the chapter of a book: sharing photos Photosare binary and have extra, interesting attributes, such as an owner and acaption In our case, photos have these pieces of metadata:
The REST service allows users to do all sorts of things with photos Forphotos you own, you can update the caption and description, and statewhether the photo is public Regardless of who you are, you can ask for alist of photos from a particular user If you are that user, the list contains allphotos 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:
{username}
{imageId}
For this chapter, we will be using the XML-based endpoint for this
serialized XML form appears as shown in Listing 3.1
An Introduction to our Web Ser vice 5
Trang 9Listing 3.1: serialized as XML
Chapter 4, “Web Client Operations,” shows the same object in JavaScriptObject Notation (JSON) format Just to show the difference here, the JSONrepresentation of the object is given in Listing 3.2
Listing 3.2: serialized as JSON
H
J
to request the actual image.) Lastly, the RESTful service validatesusers based on a username and password
Reading Data
We have lots of options for dealing with XML markup Because reading andwriting data is a big part, maybe even the biggest part, of consuming REST-ful services, the first code examples in this chapter detail how we would
mech-anism to read and write data is far beyond the scope of this book Instead,Chapter 3: Desktop Client Operations
6
Trang 10this section introduces you to the NET namespaces and tools most oftenused—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
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 H
J
Reading Data
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 ument, a database, or another storage medium Populating the
doc-class is simply for the convenience of the application’s based code Populating a form, placing data in a database, or some-thing else are also possible goals that similarly rely on the capability
C#-to extract information from an XML stream
With NET, we have lots of options for dealing with XML markup We
We can also create special classes and use the ization mechanisms offered by
7
Trang 11To demonstrate the various techniques for working with XML data, I’ve
this chapter’s demonstration solution All the XML deserialization niques just mentioned are illustrated using a static method that returns a
simplic-ity The code offers access to the XML-based representation via a
Listing 3.4: The preserialized resource
H J
The sample code demonstrates deserializing XML data using
tech-niques is executed using a simple loop that iterates a list of delegates, asshown in Listing 3.5
H
Chapter 3: Desktop Client Operations
8
Trang 12J J
has a long history with the NET Framework—it has been part
document with XML that might come from a number of sources: a file, a
scratch using code, creating each element by hand
to load an XML string or its (&:method to use XML data encodedwithin 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 helpextract data to be placed in objects for code manipulation An obviousapproach is to iterate over the contents of the document, looking for nodeswith known element names Unfortunately, this technique can be fairlycode heavy Another technique involves writing code that knows where theelement should be located within the document and then using indexers tograb the text of that node This technique winds up being very fragilebecause the layout of the document might change over time Adding ordeleting items from the document can cause specific indexes to change andcode to malfunction accordingly
The most common queries involve looking for elements or attributeswith known names Each element and attribute in the XML has an XML
Trang 13qualified name (QName) To choose a specific element or attribute, you need
to know the item’s QName The QName is consistent no matter the XMLnamespace being used
has a namespace of
default namespace with this markup:
convenience The declaration could have just as easily been
the namespace was declared, would be considered equivalent between thetwo documents What does this digression have to do with anything? Well,
if we want to ask for the caption, description, or other elements containedwithin the XML document, we have to present a name that is meaningfulvia the XPath expression These prefixes do not have to match what is in theactual XML document because XPath expressions operate against the
infoset representation of the document, not the string representation.
Chapter 3: Desktop Client Operations
NOTE
One cannot talk about XML without talking about the infoset In a shell, the infoset representation concentrates on the tree-based struc-ture of the XML document rather than what data the tree structurecontains 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, specificationauthors found it easier to write specifications because they were nolonger worrying about XML representation Developers have sinceused this to introduce new serialization schemes beyond XML 1.0(text) Today, many binary serializers have been created to reduce thebulkiness issues associated with XML
nut-10
Trang 14Knowing what we do about infosets, we need a crash course in XPath.XPath expressions can get complicated However, most queries are fairlystraightforward: Select all nodes with this name, select the first node withthis 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 givenname Example: 3:selects all nodes named 3:
• : When used as a single character, denotes that the expression starts
allows the query to select the child text nodes Example:
selects all text contents within nodes
says that the name that follows in the XPath expression is an ute Example: If we have XML such as
XPath allows for other options too You can perform logical tests such as
0, S0, =, @, 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 richsource of information for how to handle most of these deeper issues
For our example, we will want to parse all nodes with the followingQName:
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 witharticles and information about XML in general at www.xml.com
11
Trang 15To identify the prefix we will map to the namespace, we use a class
At this point, we can use additional XPath expressions to iteratively
has the benefit of being able to spin through the node data fairly quickly,
presented only for completeness because both approaches are useful An
tends to require more testing effort as changes to documentstructure can introduce bugs fairly easily, which is something to keep inmind
form of the element tag name—essentially a non-namespace version Ifyour expectation is that the names within a given node will not vary, and
Other-wise, if names in a node might be reused across XML namespaces (for
example, address could mean memory address or street address), use the
com-mon data types: strings, numbers, and Boolean values Using this
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
Chapter 3: Desktop Client Operations
12
Trang 16Listing 3.6: Reading and consuming XML using and XPath
H
<)37/:/:788 H
H F/K- J
J
J
H
<)37/:/:788 H
H H H
F/K-Reading Data
continues
13
Trang 17J
F/K-J H
J J J J
As you can see from Listing 3.6, that is an awful lot of code to translatethe XML into something readable If this RESTful services thing is evergoing to take off, there needs to be a simpler solution There is, and we willChapter 3: Desktop Client Operations
14
Trang 18get to it For this very reason, we will be skipping how to serialize data backout If you are writing the object, you have more control and better optionsthan manipulating XML documents directly for most situations, so itdoesn’t make sense to even describe how that’s done here We’ll save thattopic 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 atyour disposal You have Language Integrated Query (LINQ) LINQ ismostly syntactic sugar when represented in a NET language like C# orVB.NET The actual generated code is very procedural But, from a devel-oper point of view, the expressions are declarative Fortunately, the tech-nology has been written about enough that it is unnecessary to promote itsuse here If you do any work with LINQ, you have to go out and buy the
by Joseph and Ben Albahari, ISBN 51924-7, from O’Reilly It’s a tiny 160-page book that will literally fit into theback pocket of your jeans
978-0-596-Within LINQ, there are all sorts of variants LINQ to objects lets you cute nifty queries over collections LINQ to SQL generates SQL queries.And perhaps not surprisingly, LINQ to XML operates over XML docu-ments Specifically, LINQ to XML (XLINQ) operates on types known as
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
code:
Trang 19Most of the types we deal with in LINQ are types In ourcase, we will normally want only the first item in that list (and, in fact, theXML document we’re working with contains only one element) .NET 3.5
provides this capability quite handily Using all this basic knowledge, the
the first element from that list and pick off the 9of that item, as strated in Listing 3.7
demon-Listing 3.7: Reading and consuming XML using and XLINQ
H
H
J-
J
ver-sion First and foremost, it is a lot shorter Shorter code typically leads tofewer bugs since most developers implement code with a consistent ratioChapter 3: Desktop Client Operations
16
Trang 20of bugs to lines of code This ratio is not intentional—as humans we justtend to make mistakes at a steady pace An issue with the code in Listing 3.7
failure, the code could be rewritten as shown in Listing 3.8 to provide fordeserialization failover
Listing 3.8: Reading and consuming XML using and XLINQ with failover H
Trang 21Listing 3.8: Continued
H J H
J F/K- J
J
Again, this all depends on whether you want things to fail wheneverbad input data is encountered Most of the time, invalid data that appearsanywhere in the object implies that you do not want to continue deserial-izing that XML stream When that is the case, the short version of this code
is completely appropriate When failover is called for, however, you needthe extra code shown in Listing 3.8
-(" "!
Wouldn’t it be great if you could just tell the runtime what your objectlooked like and then it could figure out how to read the XML and populatethat object for you? As it happens, this is possible To do this, we can go to
.NET world, it is the king of XML reading and writing within the bitsshipped with the framework It handles attributes, special serialization, andschema generation Most of this work is directed with simple attributesplaced on public classes, fields, and properties And it implements the parts
of the XML Schema specification that map into NET
Chapter 3: Desktop Client Operations
18
Trang 22The most common attributes used in the are listed here:
name-space for a given property when that property appears in an XSD orXML document
namespace for a given property when that property appears in anXSD or XML document
class or enum within an XSD
class or enum when that data type is used as the root of an XMLdocument
when that enum appears in an XSD or XML document
default, all public members are serialized
Reading Data
NOTE
As it happens, NET doesn’t implement the full suite of schema structs identified in the XML Schema specification If you create aschema using a tool outside of NET, you could be asking for trouble
con-if you later try to incorporate those schemas into NET code For ple, Altova has tools with XML Spy that implement all far corners ofthe XML Schema Document specification and provide features notfound in NET If you need to support facets and other fancy features
exam-of XSD, you need to go beyond what Microsexam-oft ships with the work In practice, this kind of specialization is needed only for sophis-ticated XML processing in a small set of scenarios
frame-19
Trang 23• : Allows the developer to control the names usedwhen serializing arrays of items.
allows for a given collection to containmore than one type of object
This information is consumed by another class named
.NET types by reading these attributes via reflection The initial instance of
so quite often an instance is created early and held for the duration of theapplication’s lifetime After you have the serializer in hand, however, youcan read XML into objects and write objects as XML into a stream or filewith a single method call
right set of attributes to drastically reduce the amount of code we have towrite to eventually serialize and deserialize it The class should be deco-
The code in Listing 3.9 demonstrates these attributes in action
infor-mation as the XML element name defaults to the property name, but Iwanted to demonstrate how you establish the tie between the propertyname 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
for everyone else to use It’s a small change to the class but results in pler code overall than any mechanism seen so far
sim-Chapter 3: Desktop Client Operations
20
Trang 24Listing 3.9: with XML serialization attributes applied
With the data type decorated with all these different attributes, what
distills down to two lines of code:
H
J
Trang 25As you can see, we are no longer parsing the XML ourselves This meansthat potential bugs in the code we write become less likely—less code
elements being out of order, missing elements, and so on There is one moreserialization mechanism that has an extra benefit if you can use this mech-anism: blindingly fast speed Let’s look at that topic next
is part of afamily of serializers introduced with NET 3.0 that all inherit from
These serializers ize in reading and writing objects to XML, JSON, and other formats In gen-eral, these serializers read and write XML faster than anything else on the
however, understand that the speed comes at a price:
3L/does not handle XML attributes and it does not handle arbitrarily
fol-lowing types of data:
1/33LF
serial-izable
serializing objects that have no special attribution In this case, onlytypes with public, default constructors can be serialized The
will serialize only public fields and properties
model relies on attributes
Chapter 3: Desktop Client Operations
22
Trang 26• : Indicates that the data type has explicitserialization rules Using this attribute, one can set the way the datatype is represented in XML with a name and namespace Note thatthe namespace information might be ignored by other serializers,such as the
V&'/33L/, because JSON has no equivalent of XML spaces
read/write Besides the usual name and namespace settings, thisattribute lets the developer express the requested relative order ofthe element within any serialization scheme
collec-tion should be serialized You can set the name of the colleccollec-tion, thename of elements within the collection, and the XML namespaceassociated with the collection
elements within an enumeration
We are primarily interested in properties and related fields that use theexplicit serialization rules, which is to say have serialization attributesapplied The rest of this section focuses on the explicit aspects alone Ele-ments are ordered following these rules:
1 All elements within a type are ranked according to the value of the
property
alphabetical, ascending order By default, the value of /:/is 0
of order, it will appear with its default value (typically a 0 or null)within the deserialized object
Trang 27Assuming that you are guaranteed the order of the elements, you canuse the code shown in Listing 3.10 to read the XML information You’llprobably notice that this looks very similar to what we did for
a public, default constructor to create an object As a result, it can
Listing 3.10: with data contract attributes applied
on the same data type if you need to handleunordered XML
24
Trang 28J
method With all this information in place, we are ready tostart talking about building actual applications
Working with WinForms
There are a lot of WinForms applications out there These applications will
be improved, extended, and maintained for a long time Some of thoseenhancements and changes might need to make use of RESTful services Ifthey do, you will need to familiarize yourself with the following concepts:
provides the best overall developer tools for communicating withother HTTP-based services, although you can use the derived classes
DF&' I like the greater control I have over the request/
example: Credentials frequently need to be passed between the
chal-lenge/response pair of HTTP messages for any secured resource
, on the other hand, allows you to set its property and save a round trip
• Sharing the UI thread: NET (actually, Windows itself) gives youonly one thread for the UI If you use that single thread for synchro-nously accessing a RESTful service, the user will feel the application
is unresponsive
• Using asynchronous programming techniques: Learn to use
, the A!3'1'5&Kmethod
Trang 29for Something to keep in mind is that it’s the client that implementsasynchronous request processing To the service, a synchronousclient request is no different than an asynchronous one But yourapplication users will definitely notice the difference.
Our example here revolves around a simple WinForms application thatinteracts with the Photo Service described at the beginning of this chapter.This application does not include mechanisms for storing information to besynchronized later It only shows how to connect with the Photo Service
included with this chapter’s sample solution
This chapter also comes with a copy of the Photo Service presented later,
in Chapter 8 To install the service, please do the following:
1 Open the Chapter 3 Solution file
2 Right-click on PhotoWeb and select Publish Publish the Web cation to http://localhost/PhotoWeb
appli-3 Create the PhotoWeb database using the scripts found in the
PhotoWebDb database project You’ll find one script for creating thedatabase and another for creating all the associated tables The data-
in an authorized location or create the database using the graphicaltools found in SQL Server Management Studio, giving the new data-base the name PhotoWebDb
Let’s take a quick look at Photo Client, the WinForms sample application
that demonstrates RESTful service access When the Photo Client tion executes, the user can either log in or create a new user account Fig-ure 3.1 shows the initial application user interface
applica-Chapter 3: Desktop Client Operations
26
Trang 30Figure 3.1: WinForms startup screen
Because users might want to see the password as they type it in, theapplication allows them to show or mask the text in the password input
with a password-hiding feature they can turn on or off If the logininformation is new, which is to say unknown to the service, users can cre-ate a new service account from the Photo Client application Pressing theLogin button only caches the credentials within the application The cre-dentials are not actually submitted until the user begins to interact with thePhoto Service If the user clicks Create Account, the following tasks need
to take place:
account, providing the username, password, and e-mail address theuser provided The e-mail address might seem like an odd piece ofinformation, but the service can use this to help the user reset thepassword in the event that the user forgets the password
user-name was accepted and the password met the password strengthrequirements If the username is already in use, or if the passworddoes not meet password strength requirements, the user is notifiedand can resubmit new information
code first constructs a new URI Because the application knows exactly
Trang 31what user to create, the code uses a ;request (versus a request) Asservice application developers, we know that these are the service’s rulesfor creating a new user:
➥
is issued in the HTTP entity body as clear text, you should usetransport-level security, such as secure sockets (HTTPS), to protect it
Although not a requirement, most services provide some form of umentation that tell you, the application developer, how to interact with theservice In this case, you would be given the URI template, the XML schema(or format) for the new account request, and so forth If you’re writing aservice, you should provide this information
doc-Anyway, to call the RESTful service and create the new service user
After the request object is returned, we can change existing HTTP headervalues, add new HTTP headers, establish the HTTP method, and assignother values necessary to issue the request over the network If we donothing special, the UI thread will be using the request object, but requestsand associated responses over the network take time To allow the UI toremain responsive while the user waits for the service response, the appli-cation should use asynchronous service request techniques for any REST-ful service calls it makes The asynchronous request for creating a new user
is shown in Listing 3.11 You can tell that the request is made
synchronous counterpart)
Chapter 3: Desktop Client Operations
28
Trang 32Listing 3.11: Photo Client asynchronous user account creation H
J
Sometime later, the Photo Service responds, letting us know of anyissues or if the account creation was successful For any issues, we need tonotify the user If the account creation was successful, we let the user knowthat as well and ask if the user would like to log in
A successful response will have an associated -level status code Buthow will we know if there were issues with the request? As it happens,
response code was returned, as well as any information present in theresponse stream We can use these pieces of information to find out whatthe server told us went wrong
But hold on a minute…we’re using an asynchronous request pattern
responses via these asynchronous calling patterns, we have no knowledgeabout which application thread is being used for the response It is almost
Trang 33always a safe bet to assume that we aren’t on the original UI thread
How-ever, any code that updates the user interface must be invoked using the UI
thread This model is strictly enforced by the framework (as well as dows) and serves to prevent race conditions while updating the UI.This necessarily means we have to have some way to switch thread con-texts and gain access to the UI thread How is this accomplished? To exe-cute code on the UI thread, one technique is to invoke a parameterlessdelegate In these cases, I frequently prefer to pass along an anonymousdelegate: The code is frequently short and easier to understand whenviewed in the context of when the delegate is actually called You can call
A!3'1'5&K/':1'5&Kpair Either mechanism will make sure that yourcode runs on the UI thread, allowing your application to update the screen.For short functions, I typically call 1'5&Ksince it involves less code andI’m generally not too concerned about a short pause on the background(asynchronous) thread The callback for account creation, using
1'5&Kand an anonymous delegate, is shown in Listing 3.12
Chapter 3: Desktop Client Operations
NOTE
Failing to modify the state of the window controls via the original
the first version of Windows It’s not something we can pick andchoose to deal with—we must deal with it when creating multi-threaded Windows applications, whether NET-based or not
Listing 3.12: Asynchronous response handling
H
H30
Trang 34H J J8- J H
H
H
J
J8-
H H
J J H
J
Trang 35After we have a valid account, we can log in The application simplycaches the username and password values in memory for use when con-tacting the Photo Service Once authenticated, and if we have used the serv-ice before, we are greeted with the form shown in Figure 3.2 Note that themechanisms used to pass authentication credentials use HTTP BasicAuthentication for this service, which passes the username/password inclear text (as with account creation, which placed the password in theHTTP entity body) If your service uses HTTP Basic Authentication toauthenticate users, make sure that this is done over a secure, HTTPS chan-nel Otherwise, the credentials can be viewed by any router, proxy server,
or machine between the source and destination of the HTTP request.Chapter 3: Desktop Client Operations
Figure 3.2: The Photo Client details view
To display images coming from the service, a couple of things have tohappen First, the user needs to authenticate with the service using HTTPBasic Authentication (this will be the case for each and every RESTful serv-ice invocation) Normally this involves one or more trips to the server,
Basic Authentication and its relationship to RESTful services in Chapter 6,
“Building REST Services Using IIS and ASP.NET.”
32
Trang 36Then we make a request for images This request asks for all the imagesassociated with a particular user If the authenticated user and the userwhose images are being requested are the same, the returned list of imagesincludes all images, both public and private If the users differ, the returnedlist includes only public images associated with the requested user (Actu-ally, the list includes only the URLs that the application will use to fetch theimages The application needs to send out another batch of requests to actu-ally retrieve the image bytes.) Because we are using a RESTful service, wetreat each interaction as a brand-new request This means that each requestfor secured information, as for the list of pictures, needs to include authen-tication information.
defines a lookup table of endpoints, authentication mechanisms, and name/password combinations Fortunately,
user-implements the interface and handles our needs quite well Our code
Login button (refer to Figure 3.1), the small amount of code shown in
Listing 3.13: Photo Client Login button click handler H
H
J J
Trang 37Whenever the application needs to send an authenticated request, it can
utility method encapsulates and standardizes the code necessary for settingthe credentials It also makes sure that any outgoing requests send creden-tials on the first request—alleviating a possible challenge/response pair ofmessages between the server and the client as previously mentioned.Chapter 3: Desktop Client Operations
NOTE
Some examples later in the book, such as the client application forChapter 6, don’t use the credential cache as implemented here butrather insert the credentials directly into the HTTP request This isdone for illustrative purposes, and practically speaking is functionallyequivalent to the technique used in this chapter Feel free to usewhichever technique you prefer
Listing 3.14: The method
H
J
photo identifiers Clients have no idea what identifier the server will assign
to the new image The new identifier might be a string, an integer, or thing else—to service consumers it is just an opaque identifier When thissituation arises, from Chapter 2, “The HyperText Transfer Protocol and theUniversal Resource Identifier,” we know that RFC 2616 tells us the HTTP
some-method is appropriate After the data is posted, the client waits for theresponse so that it can discover the identifier for the newly added image.Our user interface allows the user to select files using the
When the user clicks Open, the list ofselected files is returned to the application This list is then passed to a
34
Trang 38function named is executed in a background threadobtained from the NET thread pool:
As I mentioned earlier, the )/:&& is a class you often use withasynchronous programming It allows you to spin up a thread, execute atask, and return the thread to the system with little effort on your part
increases and decreases the number of threads in an application depending
on needs and available resources Threads in the pool come into being, areused, and are reused using patterns that are efficient for the operating sys-tem For us as application developers, the good part is that all of this behav-
imple-mentation of this is shown in Listing 3.15
Listing 3.15: The method H
H
H J
Working with WinForms
continues
35
Trang 39Listing 3.15: Continued
H
J-J H
J8-
J
method to retrieve the new image identifier from the response stream, to set
con-tinue, as shown in Listing 3.16
Listing 3.16: Photo Client’s :&' method
H
H
H
/&'%&78-Chapter 3: Desktop Client Operations
36
Trang 40J J H J
J8-J
other HTTP methods Photo Client deals with, it is a matter of setting the
right resource When the Delete button is clicked (refer to Figure 3.2), thisline sets things into motion:
The )/:&&then calls , which asynchronously executes
no operating system resources are left hanging and so that the DF&'
is closed, as shown in Listing 3.17
Listing 3.17: Photo Client’s and methods H
H J
Working with WinForms
continues
37