WSDL 15An Overview of the System.Web.ServicesNamespace 17 Chapter 2 Introduction to the Setting the Start Page When testing a Web Service in a project that contains other .aspx or .asmx
Trang 2s o l u t i o n s @ s y n g r e s s c o m
With more than 1,500,000 copies of our MCSE, MCSD, CompTIA, and Ciscostudy guides in print, we continue to look for ways we can better serve theinformation needs of our readers One way we do that is by listening
Readers like yourself have been telling us they want an Internet-based vice that would extend and enhance the value of our books Based onreader feedback and our own strategic plan, we have created a Web sitethat we hope will exceed your expectations
ser-Solutions@syngress.com is an interactive treasure trove of useful
infor-mation focusing on our book topics and related technologies The siteoffers the following features:
■ One-year warranty against content obsolescence due to vendorproduct upgrades You can access online updates for any affectedchapters
■ “Ask the Author” customer query forms that enable you to postquestions to our authors and editors
■ Exclusive monthly mailings in which our experts provide answers toreader queries and clear explanations of complex material
■ Regularly updated links to sites specially selected by our editors forreaders desiring additional reliable information on key topics
Best of all, the book you’re now holding is your key to this amazing site
Just go to www.syngress.com/solutions, and keep this book handy when
you register to verify your purchase
Thank you for giving us the opportunity to serve your needs And be sure
to let us know if there’s anything else we can do to help you get the maximum value from your investment We’re listening
www.syngress.com/solutions
Trang 5Syngress Publishing, Inc., the author(s), and any person or firm involved in the writing, editing, or production (collectively “Makers”) of this book (“the Work”) do not guarantee or warrant the results
to be obtained from the Work.
There is no guarantee of any kind, expressed or implied, regarding the Work or its contents.The Work
is sold AS IS and WITHOUT WARRANTY You may have other legal rights, which vary from state
to state.
In no event will Makers be liable to you for damages, including any loss of profits, lost savings, or other incidental or consequential damages arising out from the Work or its contents Because some states do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.
You should always use reasonable care, including backup and other appropriate precautions, when working with computers, networks, data, and files.
Syngress Media®, Syngress®,“Career Advancement Through Skill Enhancement®,” and “Ask the Author UPDATE®,” are registered trademarks of Syngress Publishing, Inc “Mission Critical™,”“Hack Proofing®,” and “The Only Way to Stop a Hacker is to Think Like One™” are trademarks of Syngress Publishing, Inc Brands and product names mentioned in this book are trademarks or service marks of their respective companies.
KEY SERIAL NUMBER
Developing NET Web Services with XML
Copyright © 2002 by Syngress Publishing, Inc All rights reserved Printed in the United States of America Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.
Printed in the United States of America
1 2 3 4 5 6 7 8 9 0
ISBN: 1-928994-81-4
Technical Editor: David Jorgensen Cover Designer: Michael Kavish
Acquisitions Editor: Catherine B Nolan Page Layout and Art by: Shannon Tozier
Copy Editor: Adrienne Rebello Indexer: J Edmund Rush
Distributed by Publishers Group West in the United States and Jaguar Book Group in Canada.
Trang 6Acknowledgments
v
We would like to acknowledge the following people for their kindness and support
in making this book possible
Ralph Troupe, Rhonda St John, Emlyn Rhodes, and the team at Callisma for theirinvaluable insight into the challenges of designing, deploying and supporting world-class enterprise networks
Karen Cross, Lance Tilford, Meaghan Cunningham, Kim Wylie, Harry Kirchner, KevinVotel, Kent Anderson, Frida Yara, Jon Mayes, John Mesjak, Peg O’Donnell, SandraPatterson, Betty Redmond, Roy Remer, Ron Shapiro, Patricia Kelly, Andrea Tetrick,Jennifer Pascal, Doug Reil, David Dahl, Janis Carpenter, and Susan Fryer of PublishersGroup West for sharing their incredible marketing experience and expertise
Jacquie Shanahan, AnnHelen Lindeholm, David Burton, Febea Marinetti, and RosieMoss of Elsevier Science for making certain that our vision remains worldwide inscope
David Buckland,Wendi Wong, Marie Chieng, Lucy Chong, Leslie Lim, Audrey Gan,and Joseph Chan of Transquest Publishers for the enthusiasm with which they receiveour books
Kwon Sung June at Acorn Publishing for his support
Jackie Gross, Gayle Voycey, Alexia Penny, Anik Robitaille, Craig Siddall, DarleneMorrow, Iolanda Miller, Jane Mackay, and Marie Skelly at Jackie Gross & Associatesfor all their help and enthusiasm representing our product in Canada
Lois Fraser, Connie McMenemy, Shannon Russell, and the rest of the great folks atJaguar Book Group for their help with distribution of Syngress books in Canada
A special welcome to the folks at Woodslane in Australia! Thank you to David Scottand everyone there as we start selling Syngress titles through Woodslane in Australia,New Zealand, Papua New Guinea, Fiji Tonga, Solomon Islands, and the Cook Islands
Trang 7Contributors
Mesbah Ahmed(PhD and MS, Industrial Engineering) is a Professor ofInformation Systems at the University of Toledo In addition to teachingand research, he provides technical consulting and training for IT andmanufacturing industries in Ohio and Michigan His consulting experi-ence includes systems design and implementation projects with FordMotors, Dana Corporation, Riverside Hospital, Sears, and others
Currently, he provides IT training in the areas of Java Server, XML, and.NET technologies He teaches graduate level courses in DatabaseSystems, Manufacturing Systems, and Application Development inDistributed and Web Environment Recently, he received the University
of Toledo Outstanding Teaching award, and the College of BusinessGraduate Teaching Excellence award His current research interests are inthe areas of data warehousing and data mining He has published many
research articles in academic journals such as Decision Sciences, Information
& Management, Naval Research Logistic Quarterly, Journal of Operations Management, IIE Transaction, and International Journal of Production Research.
He has also presented numerous papers and seminars in many nationaland international conferences Mesbah is a contributor to Syngress
Publishing’s ASP NET Developer’s Guide (ISBN: 1-928994-51-2).
Patrick Coelho(MCP) is an Instructor at The University of WashingtonExtension, North Seattle Community College, Puget Sound Center, andSeattle Vocational Institute, where he teaches courses in Web
Development (DHTML, ASP, XML, XSLT, C#, and ASP.NET) Patrick is
a Co-Founder of DotThatCom.com, a company that provides consulting,online development resources, and internships for students He is cur-rently working on a NET solution with contributing author DavidJorgensen and nLogix Patrick holds a bachelor’s of Science degree fromthe University of Washington, Bothell Patrick lives in Puyallup,WA withhis wife, Angela Patrick is a contributor to Syngress Publishing’s
Trang 8ASP.NET Developer’s Guide (ISBN: 1-928994-51-2), C# NET Web Developer’s Guide (ISBN: 1-928994-50-4), and NET Mobile Web Developer’s Guide (ISBN: 1-928994-56-3).
Adrian Turtschi(MCSD, MCSE) was formerly employed by KPMGInternational/CERING as an Integration Architect He was responsiblefor integration of components, services and third-party applications ofKPMG’s next generation global knowledge management and collabora-tion solution (KnewPro) KnewPro is an application supporting collabora-tion between geographically and organizationally distributed teams,integrating knowledge sharing and content management, team collabora-tion, enterprise search, workflow, and legacy data connectivity Adrian alsoco-wrote the KnewPro architecture document Prior to joining KPMG,
he worked for EBSCO Publishing as a Software Engineer Adrian is rienced with Java, C#,Visual Basic, Pascal, and the NET Framework as amember of the Early Adopter program Adrian is a contributor to
expe-Syngress Publishing’s C# NET Web Developer’s Guide (ISBN:
1-928994-50-4) He is fluent in English, French, German, and Italian He has done
presentations and has published articles with XML Journal, Nature, and
Exchange & Outlook Magazine Adrian graduated with a master’s of Science
in Computer Science and Mathematics from the University of Bern,
School of Science, Bern, Switzerland and a master’s of Arts in
Mathematics from Brandeis University, Graduate School of Arts andSciences,Waltham, MA.He resides in Germany
Trang 9David Jorgensen (MCP) David works for Alliance Enterprises, Inc inOlympia WA, which develops Web-based case management software forsocial service organizations such as state vocational rehabilitation agencies.His latest project; convert a state agencies data, involved complex SQLServer Data Transformation Packages David holds a bachelor’s degree inComputer Science from St Martin’s College and resides in Puyallup,WAwith his wife, Lisa and their two sons, Scott and Jacob David is a contrib-
utor to Syngress Publishing’s C# NET Web Developer’s Guide (ISBN: 1-928994-50-4), and the NET Mobile Web Developer’s Guide
(ISBN: 1-928994-56-3)
Technical Editor and Contributor
Trang 10WSDL 15
An Overview of the System.Web.ServicesNamespace 17
Chapter 2 Introduction to the
Setting the Start Page
When testing a Web
Service in a project that
contains other aspx or
.asmx files, be sure to set
the file you are debugging
or testing as the Start
page, before running To
do this, right-click the
filename in the Solution
Explorer and select Set as
start page.
Trang 11Additional Installation Information 33Locations for Downloading 34Installing the NET Framework 34Common Language Runtime 36Major Responsibilities of the CLR 36Safety and Security Checks 37
Object Lifetime Management 37Just In Time (JIT) Compilation 38Cross-Language Interoperability 38Structured Exception Handling 39Assemblies 39Metadata 40Enhanced Deployment and Versioning
Support 41Managed versus Unmanaged Code 41Interoperability with Unmanaged Code 42Namespaces 42Developing Applications with the
Summary 62Solutions Fast Track 63Frequently Asked Questions 65
NT 4.0 server you must
have service pack 6a
applied.
Q: Where can I find the
install for ASP.NET?
A: ASP.NET ships as part
of the NET Framework
SDK.
Trang 12in VS.NET XML Designer 71Components of an XML Document 72Well-Formed XML Documents 75Schema and Valid XML Documents 76Structure of an XML Document 80Processing XML Documents Using NET 81Reading and Writing XML Documents 82Storing and Processing XML Documents 83Reading and Parsing Using the
XmlTextReader Class 84
Parsing an XML Document 85Navigating through an XML
Document to Retrieve Data 87Writing an XML Document
Using the XmlTextWriter Class 90
Generating an XML Document
Using XmlTextWriter 90Exploring the XML Document Object Model 93
Navigating through an XmlDocument Object 94
Parsing an XML Document
Using the XmlDocument Object 95 Using the XmlDataDocument Class 98 Loading an XmlDocument and
Retrieving the Values of Certain Nodes 99Using the Relational View of
an XmlDataDocument Object 100
Viewing Multiple Tables of
a XmlDataDocument Object 103 Querying XML Data Using XPathDocument
Components of an XML Document
■ Schema or Document Type Definition (DTD)
In certain situations, a schema or DTD may precede the XML document
■ Elements An XML
document is mostly composed of elements.
■ Root Element In an
XML document, one single main element must contain all other elements inside it This specific element is often called the root element.
■ Attributes An
attribute is just an additional way to attach a piece of data
to an element.
Trang 13Using XPathDocument and
Using XPathDocument and XPathNavigator
Objects for Document Navigation 112Transforming an XML Document Using XSLT 115Transforming an XML Document to
an HTML Document 116Transforming an XML Document
into Another XML Document 119Working with XML and Databases 124Creating an XML Document
from a Database Query 125Reading an XML Document into a DataSet 127Summary 129Solutions Fast Track 129Frequently Asked Questions 133
Chapter 4 Information Exchange Using the Simple Object Access Protocol (SOAP) 135
Introduction 136The Case for Web Services 136
Malformed SOAP Request 163Wrong Argument Types 165Exceptions in Server Code 165Writing a SOAP Client Application 167
Passing Relational Data (DataSets) 179
Showing All Files
through the Solution
Explorer
Trang 14Passing XML Documents 182
Advanced Web Services 187Maintaining State 187State Information in the URL
(URL Mangling) 189State Information in the Http
Header (Cookies) 191State Information in the Http
Body (SOAP Header) 194Security 202Summary 204Solutions Fast Track 205Frequently Asked Questions 207
Introduction 210Web Service Standards 211Describing Web Services—WSDL 211Discovering Web Services—DISCO 217Publishing Web Services—UDDI 219Working with UDDI 220Summary 228Solutions Fast Track 229Frequently Asked Questions 231
Chapter 6 Building an ASP.NET/ADO.NET Shopping Cart with Web Services 233
Introduction 234Setting Up the Database 234
Setting Up the Table Books 237
Setting Up the Table Categories 237
Setting Up the Table Customer 237
Setting Up the Table Orders 238
Setting Up the Table BookOrders 238
Creating an Access Database 238SQL Server Database 242Creating the Stored Procedures 244
Web Services
Web Services are different from previous technolo- gies used to create distrib- uted systems, such as COM/DCOM, in that:
■ They use open standards.
■ They were designed from the ground up to work on the Internet, including working well with corporate firewalls.
■ They use a “simple”
protocol not requiring multiple round trips to the server.
■ They purposefully don’t address advanced features such as security or transaction support as part of the protocol specification.
Trang 15Creating the Web Services 250Overview of the Book Shop Web Services 250Creating the Data Connection 252Creating a Web Service 253Testing a Web Service in ASP.NET 259Using WSDL Web References 263
Site Administration 266Creating the Administration Login
(adminLogin.aspx) 266Creating the Administrator
Page (adminPage.aspx) 268Retrieving the Data: Creating the
getBooks.AllBooks Web Method 268Displaying the Data: Binding
a DataGrid to the DataSet 272Adding New Books to the Database:
Creating the allBooks.addItem
Deleting Books: Deleting from
the DataGrid and the Database 272Updating Book Details: Updating
the DataGrid and the Database 273Creating the addBook Page (addBook.aspx) 274Customer Administration 275Creating the Customer Admin Section 275
Creating the loginCustomer Page 275 Creating the updateCustomerInfo Page 276
catalogRange, and catalogByCategory
Methods 281
Answers to Your
Frequently Asked
Questions
Q: My project has a few
different pages in it.
Unfortunately, the last
page I created is the
one that is loaded
when I run the project.
How do I set the first
page to open when I
run the project?
A: In your Project
Explorer, right-click
the file you want and
set it as the Start
Page.
Q: I am working with the
XmlDocument object in
my code-behind page,
and I am not getting
any IntelliSense What
am I doing wrong?
A: Make sure you have
included “Using
System.Xml” in the top
section of the page.
Trang 16Creating the catalogRangeByCategory
Method 282Building an XMLCart 284Creating the User Interface 287Creating the start.aspx Page 288Rendering the Catalog 289Rendering the Cart 290Creating the Code 290Summary 293Solutions Fast Track 293Frequently Asked Questions 297
Chapter 7 Building a SQLXML
Introduction 300SQLXML Web Services 301Developing the TimeTrack Application 301Creating the Database 302Creating the Stored Procedures 303Creating a SQL Server Virtual Directory 305Enabling Stored Procedures for Soap 310Creating a Client Application in ASP.NET 313Consuming the Web Services 317Summary 333Solutions Fast Track 334Frequently Asked Questions 335
Chapter 8 Building a Jokes Web Service 337
Introduction 338Motivation and Requirements for the Jokes
Functional Application Design 340Defining Public Methods 340Defining the Database Schema 341Defining the Web Service Architecture 342Security Considerations 344State Management 345
Configuring &
Implementing…
SQL Template Queries
Previously accessing SQL Templates server-side from within an ASP.NET
application would fail to load the XML because the security context of the user would be lost when hopping from IIS to SQL.
SQLXML 3.0 solves this problem by allowing server-side access to Template queries by
setting SqlXmlCommand
.CommandType = SqlXmlCommandType TemplateFile.
Trang 17Error Handling 345Implementing the Jokes Data Repository 345Installing the Database 346Creating the Stored Procedures 348Implementing the Jokes Middle Tier 361Setting Up the Visual Studio Project 361Developing the Error Handler 366Developing the Database Access Component 369Developing the User Administration Service 371Adding New Users 371Checking Existing User Information 376Adding Moderators 379Creating the Public Web Methods—Users 381Error Handling for the Public Web
Methods 384Creating The Public Web Methods—
Administrators 386Testing the Public Web Methods 389Developing the Jokes Service 390Best Practices for Returning Highly
Structured Data 390Setting Up Internal Methods to
Wrap the Stored Procedure Calls 393Setting Up Internal Methods
to Manage Jokes and Ratings 399Setting Up Internal Methods to
Creating the Public Web Methods 413Creating a Client Application 423Some Ideas to Improve the Jokes
Summary 440Solutions Fast Track 441Frequently Asked Questions 443
Error Handling for the
Public Web Methods
The throwFault method
throws a SOAP fault and
ends execution of the Web
Service method But it
does a whole lot more:
■ The (internal) error
custom element, called
failReason, where client
applications can find
the error message to
display to users.
Trang 18Since it’s inception in February of 1998, XML has been moving forward through thecontinued efforts of the World Wide Web Consortium (W3C) At first many devel-opers scoffed at XML, thinking it was just a new way to script However, thosedevelopers, who regularly worked with database management and development soonrealized that XML could be a way to provide data between parties without needing
to rely on proprietary solutions
At first, this handful of developers began to incorporate snippets of XML intotheir desktop applications to store configuration data or as an export file As timepassed, developers began to apply XML to the Internet Databases began to commu-nicate to each other via XML, and companies were discovering that they had aneasier time coping with external database data thanks to XML
Developers, however, were not the only ones that noticed the possibilities ofXML Microsoft realized the potential of XML, and made it one of the cornerstones
of the NET Framework .NET aims to bridge the gap between desktop applicationsand online applications, and facilitate the communication of objects between the two
At the same time, the concept of Web Services was being developed.
Broadly speaking, a Web Service is the exposure of a business process over a work.The connotation is generally that XML-based traffic is being moved on apublic network (the Internet) via the HTTP protocol However,Web Services canalso be internally useful to an organization, as a mechanism for encapsulating andexposing the business logic inherent in legacy systems New applications can thenutilize this Web Service interface to leverage the complex business logic that has beenrefined, sometimes for decades, in these legacy systems.This allows for the reuse ofsystems at the logical level, without regard to physical configuration
net-Web Services are a fundamental part of the new NET Framework.You can
group Web Services into two categories: producers and consumers A producer Web
Service is one that will retrieve a result set, for instance orders from an e-commerce
xvii
Foreword
Trang 19database, or Jokes; as in Chapter 8 “Building a Jokes Web Service” A consumer WebService is one that will use that result set of data and do something with it, as in theshopping cart example in Chapter 6 “Building an ASP.NET/ADO.NET ShoppingCart with Web Services.” In this book we will examine both and provide examples ofeach.This book focuses on all aspects of Web Services including: XML, SOAP,
WSDL, UDDI, and the NET Framework
However,Web Services are not limited to just the NET framework and
Microsoft IBM, SUN, and Oracle will all be players in this fast changing ment.The W3C is still working on revisions for SOAP and XML, which means thatthis subject matter is continuously evolving
environ-Taking this a step further, databases will be leveraging their objects as Web
Services, as shown in Chapter 7 “Building a SQLXML Web Service.”This is a
growing segment of Web Services and XML Using the universal versatility of XML,
an application can transport data across multiple platforms and achieve the sameresults Encapsulating this logic in Web Services adds functionality to both the appli-cation and the database
This book assumes that you have prior experience with XML.The code tained in the examples will be in both C# and VB.NET.We will also take a look atSQLXML Web Services along with ADO.NET.You do not have to be a guru to buythis book, but you should possess object oriented programming knowledge to get themost benefit from the code examples If you have any experience in programming atall you should be able to pick up the content easily If you need a more fundamental
con-start, I suggest picking one of these two books, VB.NET Developer’s Guide (ISBN: 1-928994-48-2) and the C# Web Developer’s Guide (ISBN: 1-928994-50-4) Both of
these books offer the proper foundation to properly leverage the knowledge and
information in Developing NET Web Services with XML.
—David Jorgensen, MCP
www.syngress.com
Trang 20The Syngress Solutions Web site (www.syngress.com/solutions) contains the codefiles, applications, sample databases, and Web Services that are used throughout
Developing NET Web Services with XML.
The code files are located in a chXX directory For example, the files for Chapter
3 are located in folder ch03 Any further directory structure depends upon the WebServices and applications that are presented within the chapter Some of the notablepieces of code include those found in Chapters 6 through 8
In Chapter 6, “Building an ASP.NET/ADO.NET Shopping Cart with WebServices,” readers will find all of the code needed to create a fully functional applica-tion for an online bookseller, that is capable of authenticating users and querying adatabase of both customers and products
Chapter 7, “Building a SQLXML Web Service Application,” includes all of thecode used to create a Web Service for the purpose of project management called
“TimeTracker.”
Finally, Chapter 8, “Building a Jokes Web Service,” includes all of the codeneeded to create a Web Service for interaction between a database of clients, andcontent Code for the GUI is included as well
Look for this icon to locate the code files that will be included on our Web site.
About the Web Site
Trang 22What Are Web Services?
Solutions in this chapter:
■ Understanding Web Services
■ Using XML in Web Services
■ An Overview of the System.Web.Services Namespace
; Solutions Fast Track
; Frequently Asked Questions
Trang 23Web Services provide a new level of interaction to all kinds of applications.Theability to access and use a remote Web service to perform a function within anapplication enables programmers to quickly deliver a more sophisticated applica-tions in less time.The programmer no longer has to create and maintain all func-tions of the application Reusability is also greatly enhanced by creating multipleWeb services that perform functions in multiple applications, thus freeing up timeand resources to work on other aspects of specific projects See Figure 1.1, whichshows a graphical representation of this process
www.syngress.com
Figure 1.1Where Do Web Services Fit In?
Host Web Services
Internet and Database Servers
Data
Host Web Pages
Internet Servers IIS
Host Web Pages Host Web Pages
Trang 24In this chapter we will be looking at a simple Hello World Web Service ered via ASP NET.This Web Service example can be accessed by any applicationthat can handle Simple Object Access Protocol (SOAP).
deliv-Web Services function primarily through XML in order to pass informationback and forth through the Hypertext Transfer Protocol (HTTP).Web Servicesare a vital part of what the NET Framework offers to programmers XML-baseddata transfer is realized, enabling primitive types, enumerations, and even classes to
be passed through Web Services to the application performing the request.Thisbrings a whole new level of reusability to an application XML is the backbonefrom which the whole Framework is built.The user interface (UI) can be created
by applying Extensible Stylesheet Language Transformations (XSLTs) or by
loading the data into DataSets and binding to Web Controls Having XML as the
intermediary enables new avenues of client design
Understanding Web Services
Web Services are objects and methods that can be invoked from any client overHTTP.Web Services are built on the Simple Object Access Protocol (SOAP)
Unlike the Distributed Component Object Model (DCOM) and Common ObjectRequest Broker Architecture (CORBA), SOAP enables messaging over HTTP onport 80 (for most Web servers) and uses a standard means of describing data SOAPmakes it possible to send data and structure easily over the Web.Web Services capi-talizes on this protocol to implement object and method messaging.Web Services
are easy to create in VS.NET Here is an ASP.NET Hello World class in C#:
public class hello {
public string HelloWorld() {
return "Hello World";
} } }
This class describes a hello object that has one method, HelloWorld.When called, this method will return data of type string.To convert this to a Web Service
method, we simply have to add one line of code:
public class hello {
Trang 25A little bit more code is involved to make this a method of a Web Service.This is the code that VS.NET auto-generates when we create a new asmx page,
along with our Hello World method:
InitializeComponent();
} private void InitializeComponent() {
} protected override void Dispose( bool disposing ) {
} [WebMethod]
public string HelloWorld() {
return "Hello World";
}
www.syngress.com
Trang 26} }
You can quickly create this class in VS.NET by creating and opening a C#
Web Application project or Web Service project and adding a new WebServicepage
If you prefer, similar code could be written to create a VB.NET Service:
Imports System.Web.Services
Public Class Service1 Inherits System.Web.Services.WebService
<WebMethod()> Public Function HelloWorld() As String
HelloWorld = "Hello World"
End Function
End Class
To run this sample in VS.NET, simply press F5 It will take a few moments to
build and compile.When that phase is complete, you should see the Hello servicescreen shown in Figure 1.2
The top line on the screen states that the operations listed below it are ported.This is followed by a bulleted list of links to each of the Web methodsthat belong to the Web service In our case, we created only one Web method,
sup-HelloWorld If you click the link HelloWorld, you will be taken to that service’s
description page (see Figure 1.3)
Setting the Start Page
When testing a Web service in a project that contains other aspx or asmx files, be sure to set the file you are debugging/testing to be the Start page, before running To do this, right-click the filename in the
Solution Explorer and select Set as start page.
Debugging…
Trang 27Figure 1.2Hello Service
Figure 1.3HelloWorld Service Description Page
Trang 28To test our Hello Web Services HelloWorld Web method, simply click the
Invoke button and our method will be called Recalling our method returns thestring “hello world”; the result is returned in an XML wrapper (see Figure 1.4)
Note that the XML node reflects the datatype of the method’s return value,
string.This XML message is received and converted to the string “Hello World”.
This means that any variable (of type string) in our code can be assigned to the
result of our Web method
Figure 1.4Results from Invoking the HelloWorld Web Method
Building and Compiling
If you have experience programming in C/C++ or Java, you will be familiar with the building and compiling steps If you are a Web Developer who hasn’t really played with a compiled language before, these steps will be new to you Think of it as the phase in which the com- piler gets all your code together and checks it for unassigned variables, variable type mismatches, and other syntactic errors In this phase, it also converts your code into the Common Language Runtimes (CLR) Intermediate Language (IL), and then into machine language This will allow the code to run faster and more efficiently than uncompiled script.
After this phase completes, the code is run in the Browser So, testing Web page output may seem to take longer in the NET environment.
Developing & Deploying…
Trang 29Communication between Servers
The concept of sending messages between servers or remotely calling functions isnot new.Technologies such as DCOM and CORBA are well-known proprietaryprotocols that have been in use for years.What is new is the use of a standardprotocol to transfer messages over HTTP, that protocol is SOAP SOAP makes itpossible for applications written in different languages running on different plat-forms to make remote procedure calls (RPC) effectively, even through firewalls.DCOM doesn’t use port 80, which is reserved for HTTP traffic; this causesDCOM calls to be blocked by firewalls SOAP calls use port 80, which makes itpossible to call procedures that exist behind firewalls Figure 1.5 shows a highlevel overview of how Web Services can be used, both for customer interactionswith a company from multiple client types as well as for internal company datagathering and reporting between all company servers, including legacy systems
Server Data
Branch Office
Server Data
Customers
Corporate / Customer Web Services
Corporate Reporting Web Services
Investment Brokerage House
Customer Web Services Branch kiosk can allow customers to pull or retrieve account information.
Corporate Website can allow customers to pull or retrieve account information.
Corporate Web Services Branch offices can push reporting data to corporate servers.
Corporate can pull branch reporting data.
Soap / HTTP Using SOAP over HTTP enables servers running different operating systems to communicate seamlessly over the Internet.
Soap / HTTP Using SOAP over HTTP enables applications written in different languages to communicate seamlessly over the Internet.
Trang 30In ASP.NET,Web Services and their methods are defined in pages with the.asmx extension.When we create Web Services, the NET Framework generates aWeb Services Description Language (WSDL) file on the server hosting theService; this WSDL file describes the Web Service interface On the Web server
that hosts our aspx pages,VS.NET generates a WSDL proxy when we click Add
Web reference in the Solutions Explorer and select the server and Service
Customers
WSDL Server Data
Scenario Web user makes an online purchase:
• One method call could verify and process the credit card with a Web Service supplied by the credit card organization.
• Another method could contact a Web service supplied by the shipping company to calculate shipping charges.
• Another Web service from within the organization could remove the item from active inventory and flag it for shipping.
Trang 31A single application hosted on the Web server may access several Web Services residing on different servers Likewise, many Web servers may access one Web Service.
.asmx Files
ASP.NET uses the asmx file extension for defining ASP.NET Web Services.Thecode-behind pages are asmx.cs and asmx.vb for C# and VB.NET, respectively
www.syngress.com
Figure 1.7Web References in VS.NET’s Solution Explorer Window
What Is the Difference between asmx and aspx?
In ASP, we have the asp extension to denote an Active Server Page When IIS sees this extension, it knows it has some extra processing to
do This is the same with ASP.NET, except that we have two new sions, aspx and asmx.
exten-Migrating…
Continued
Trang 32While the client for an aspx page is the Web browser, the client for an asmxfile is the Web server Since they are used as programming interfaces and notdirectly utilized by the Web user, asmx files should not contain any UI.To get abetter understanding of how this all works, lets create an aspx page that calls our
“Hello” service
1 In the Solutions Explorer, right-click the project name.
2 Select Add | New Item.
3 Select Web Form Name the file helloPage.aspx.
4 While in design view, open the toolbox and drag onto the page a labeland a button control from the selection of Web Forms (see Figure 1.8)
While still in design mode double-click the new button.This willgenerate event code in the code behind page (see Figure 1.9)
5 Right-click References in the Solution Explorer and select Add
Web Reference.This is basically a graphical user interface (GUI) forthe WSDL.exe command line utility
Lets do a quick comparison:
■ Both file types have a template, which includes references to the primary namespaces.
■ aspx pages have references to System.Drawing since their purpose is to generate a user interface.
■ asmx pages have references to System.Web.Services since their purpose is to generate an interface for external pro- grams.
■ You can add UI components and DataConnections to an aspx page.
■ You can add Server and DataConnections to an asmx page.
■ aspx pages usually begin with an @Page directive to nate: this is a WebForm.
desig-■ asmx pages usually begin with an @WebService directive to designate: this is a Web Service.
■ Using the wrong @ directive with the wrong type of file extension will generate an error.
Trang 33Figure 1.8Adding a Web Form Control to an aspx Page
Figure 1.9Auto-generated Button Event Code
Trang 346 When the Add Web Reference dialog opens (see Figure 1.10) click the link Web References on local server.
The dialog will pause while it searches your local machine for a list
of services available
7 When the list appears, click the name of the service that matches the
name of your project, WebApplication_HelloWorld.
8 When the service loads, click the Add Reference button.This will
create several new entries in your Solutions Explorer
9 Now take a look at helloPage.aspx in HTML view.You should see codesimilar to the following:
<body MS_POSITIONING="GridLayout">
<form id="helloPage" method="post" runat="server">
<asp:Button id=Button1 Text="Button" runat="server" >
Trang 3510 Note the name of the label control is Label1 Now open
helloPage.aspx.csand add the following code below the label andbutton code
localhost.hello test = new localhost.hello();
11 In the Button Click handler, add the following:
Label1.Text = test.HelloWorld();
12 Your code should now look like Figure 1.11
13 Right-click helloPage.aspx and click Set as start page.
14 Press F5 to run the application.
15 When the browser loads, click the button, this will invoke our helloWorld
method and assign its value to the label text After clicking the button,your page should look like Figure 1.12
www.syngress.com
Figure 1.11helloPage.aspx.cs
Trang 36WSDL is an XML-based language that describes Web Services It is the posite of work done by Ariba, IBM, and Microsoft Currently, it only supportsSOAP as a messaging protocol
com-The thought behind WSDL is that in future applications it will be a tion of networked-Web Services.WSDL describes what a service can do, where itlives, and how to invoke it.WSDL describes the Web Service method interfacesthoroughly enough for it to be used to create proxy methods that enable otherclasses to invoke its members as if they were local methods IBM and Microsoftboth have WSDL command line utilities available that do just that IBM does itfor Java, and Microsoft does it for Visual Studio.VS.NET has this ability built into
collec-the GUI In VS.NET, we simply right-click add Web Reference and select collec-the
service we want to generate a proxy class for Here is an example of a WSDL filefor a Web Service: getCategories.wsdl.This file is auto-generated by the NETFramework
While the auto-generated file will cover the basic functionality, it may domore or less than you intended.The auto-generated code can be simplified byremoving support for asynchronous operations if you do not need to support thistype of operation Also, you could add custom SOAP headers and customizeother parts of the SOAP envelope by creating your own class WSDL and UDDIare covered in later chapters
Figure 1.12HelloPage.aspx in the Browser after Clicking the Button
Trang 37Using XML in Web Services
Web Services use SOAP as a messaging protocol SOAP is a relatively simpleXML language that describes the data to be transmitted.Why use XML? XML
is a standard language designed to be understandable by humans, and structured
so it can be interpreted programmatically XML does not only describe data, itcan also describe structure, as we will see when we take a closer look at the
ADO.NET DataSet.
Consider the case of replicating a database into cache.We might want to dothis to reduce the load on the database server, to speed client processing, or toprovide an offline data handling scenario.We could transport an XML documentthat contains the new W3C XML Schema Definition Standard (XSD) schemadescribing the database tables, relations, and constraints, along with the actual data(see the section “Using DataSets” later in this chapter) Because XSD can
describe relational data and can be embedded within an XML document, anydatabase can be converted to a ubiquitous data source.That is, a data source thatcan be accessed on any platform by any application.This is possible because thetransfer protocol, SOAP, uses XML over HTTP and because XML, XSD, SOAP,and HTTP are all nonproprietary industry standards
It is the use of non proprietary industry standards that makes Web Services sopowerful By using XML to describe structure and content,Web Services canprovide an interface to data on legacy systems, or between incompatible platformsfrom acquisitions or between vendors over intranets, extranets, or the Internet
Trang 38An Overview of the System.Web.Services Namespace
System.Web.Services is the namespace from which all Web service classes are
derived It consists of all the classes needed to create Web Services in the NET
Framework.When using VS.NET most of the System.Web.Services classes and
sub-classes are transparent to the developer, so we won’t go into much depth here
The three primary child classes of System.Web.Services are: Description, Discovery,
and Protocols
The System.Web.Services.Description Namespace
The System.Web.Services.Description namespace contains the classes needed to
describe a Web Service using the Microsoft SDL (Service Definition Language), aMicrosoft implementation of the WSDL standard.VS.NET uses these classes tocreate the disco or vsdisco file Many of the subclasses of this class are related tobinding: MessageBinding, OperationBinding, OutputBinding, and so on One of
the more interesting subclasses is the ServiceDescription class It takes as a parameter
an XML file and enables the creation of a valid WSDL file
ServiceDescription MyDescription = new ServiceDescription();
ServiceDescription MyDescription =
ServiceDescription.Read("MyTestFile.xml");
The System.Web.Services.Discovery Namespace
The System.Web.Services.Discovery namespace consists of the classes that enable
Web Service consumers to locate available Web Services In VS.NET when wecreate a Web Reference, these classes find the vsdisco files that describe WebServices
Disco file from our Hello World example:
docRef="http://localhost/WebApplication_HelloWorld/hello.asmx"
Trang 39xmlns="http://schemas.xmlsoap.org/disco/scl/" />
</discovery>
The System.Web.Services.Protocols Namespace
The System.Web.Services.Protocols namespace consists of the classes used to define
the protocols that enable message transmission over HTTP between ASP.NETWeb Services and ASP.NET Web Service clients.These classes are used in ourWSDL proxy classes.They are mostly involved with the formatting, bindings, andsettings of the SOAP message
WSDL proxy from our Hello World example:
"http://localhost/WebApplication_HelloWorld/hello.asmx"; }
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute(
"http://tempuri.org/HelloWorld", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=
System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string HelloWorld() {
object[] results = this.Invoke("HelloWorld", new object[0]);
www.syngress.com
Trang 40return ((string)(results[0]));
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
public System.IAsyncResult BeginHelloWorld(
System.AsyncCallback callback, object asyncState) {
Type Marshalling
Type marshalling refers to the translation of datatypes from an application or
database as it is mapped to a SOAP datatype.When any datatype, object, method,
or string (xml, or a simple string) is passed as a SOAP request or response, it isautomatically converted into an XML representation of itself Since any program-ming language can use SOAP, SOAP has defined its own set of datatypes.Whendata is passed in a SOAP envelope its datatypes are translated or converted to aSOAP equivalent.This enables different languages with different names for similardatatypes to communicate effectively.The datatypes supported when using WebServices include:
■ Standard primitive types String, char, Boolean, byte, single, double, DateTime, int16, int32, int 64, Uint16, and so on.
string "hello World" is represented as:
<string>hello World</string>