web services using c# and asp - itcourseware · web services using c# and asp.net rev. 3.0 ......

94
Object Innovations Course 4150 Student Guide Revision 3.0 Web Services Using C# and ASP.NET

Upload: phamcong

Post on 08-Apr-2018

230 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Object Innovations Course 4150

Student Guide Revision 3.0

Web Services Using C# and ASP.NET

Page 2: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC ii All Rights Reserved

Web Services Using C# and ASP.NET Rev. 3.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Authors: Robert J. Oberg, Arun Ganesh, Will Provost Special Thanks: Paul Nahay, Sharman Staples Copyright ©2009 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Published in the United States of America.

Page 3: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 What Are Web Services? Chapter 2 Web Services Fundamentals Chapter 3 Developing ASP.NET Web Services Chapter 4 Web Service Clients Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization Chapter 7 More about SOAP Chapter 8 More about WSDL Chapter 9 Data Access with Web Services Chapter 10 Introduction to WCF Appendix A Learning Resources Appendix B Configuring IIS for ASP.NET

Page 4: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• Install the course software by running the self-extractor Install_WsNetCs_30.exe.

• The course software installs to the root directory C:\OIC\WsNetCs.

− Example programs for each chapter are in named subdirectories of chapter directories Chap02, Chap03 and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The Demos directory is provided for performing in-class demonstrations led by the instructor.

− Deploy is for testing deployment of a Web service to a different directory from the one in which it was created.

• Data files install to the directory c:\OIC\Data.

• Log files are written to the directory c:\OIC\Logs.

Page 5: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1: What Are Web Services?.................................................................................. 1 What is a Web Service? ...................................................................................................... 3 Why are Web Services Needed?......................................................................................... 4 Distributed Object Computing............................................................................................ 5 Major Players in Web Services......................................................................................... 10 Web Services Interoperability .......................................................................................... 11 Benefits of Web Service Integration................................................................................. 12 SOAP ................................................................................................................................ 13 UDDI................................................................................................................................. 15 Web Services Business Models ........................................................................................ 16 Business Models Classified .............................................................................................. 17 Service Oriented Architecture (SOA)............................................................................... 18 Services Are Independent ................................................................................................. 19 ASP.NET Web Services ................................................................................................... 20 Alternative Technologies.................................................................................................. 21 Web Service Enhancements 3.0........................................................................................ 22 Windows Communication Foundation ............................................................................. 23 Summary ........................................................................................................................... 24

Chapter 2: Web Services Fundamentals .......................................................................... 25 Understanding Web Services............................................................................................ 27 Internet Information Services ........................................................................................... 28 Internet Services Manager ................................................................................................ 29 Virtual Directory............................................................................................................... 30 Anonymous Access........................................................................................................... 32 Home Page for Example Programs................................................................................... 33 IIS Applications ................................................................................................................ 34 An Echo Web Service....................................................................................................... 35 Echo Web Service Using ASP.NET ................................................................................. 36 Running Web Service Example ........................................................................................ 37 SOAP Request .................................................................................................................. 38 Testing the Web Service ................................................................................................... 39 HTTP POST Request ........................................................................................................ 40 Hypertext Transfer Protocol (HTTP)................................................................................ 41 HTTP Headers and Content .............................................................................................. 42 HTTP Methods.................................................................................................................. 43 XML.................................................................................................................................. 44 SOAP-Based Web Services .............................................................................................. 45 Messaging Models ............................................................................................................ 46 Messaging Over the Web.................................................................................................. 47 The SOAP Messaging Model ........................................................................................... 48

Page 6: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC vi All Rights Reserved

SOAP Namespaces ........................................................................................................... 49 The SOAP Envelope ......................................................................................................... 50 The Message Header......................................................................................................... 51 Header Entry Attributes .................................................................................................... 52 The Message Body............................................................................................................ 53 Service Descriptions ......................................................................................................... 54 Web Services Description Language................................................................................ 55 Viewing WSDL ................................................................................................................ 56 Using WSDL..................................................................................................................... 57 wsdl.exe in .NET SDK...................................................................................................... 58 Demo: A Web Services Client .......................................................................................... 59 Lab 2 ................................................................................................................................. 60 Summary ........................................................................................................................... 61

Chapter 3: Developing ASP.NET Web Services .............................................................. 65 Developing Web Services in Visual Studio 2008............................................................. 67 Visual Studio Web Service Demo .................................................................................... 68 Code for a Simple Web Service........................................................................................ 70 Hello World Web Service................................................................................................. 71 Concatenate Web Service ................................................................................................. 72 WebService Directive ....................................................................................................... 77 Service.cs .......................................................................................................................... 78 System.Web.Services Namespace .................................................................................... 79 WebService Attribute ....................................................................................................... 80 WebMethod Attribute ....................................................................................................... 81 BufferResponse................................................................................................................. 82 MessageName................................................................................................................... 83 Basic Profile...................................................................................................................... 86 Turning Off Conformance Checking ................................................................................ 87 WS-I Basic Profile ............................................................................................................ 88 ASP.NET Configuration ................................................................................................... 89 Multi-level Configuration ................................................................................................. 90 Configuration Hierarchy ................................................................................................... 91 Lab 3A .............................................................................................................................. 92 WebService Class ............................................................................................................. 93 Sample Program – Utility ................................................................................................. 94 Lab 3B............................................................................................................................... 97 Lab 3C............................................................................................................................... 98 Summary ........................................................................................................................... 99

Chapter 4: Web Service Clients ...................................................................................... 113 Protocols ......................................................................................................................... 115 Accessing a Web Service................................................................................................ 116 Creating a Proxy ............................................................................................................. 117 Creating a Proxy using wsdl.exe..................................................................................... 118 Exploring the Generated Proxy Code ............................................................................. 119

Page 7: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC vii All Rights Reserved

Console Client Test Program.......................................................................................... 122 Creating a Proxy via Visual Studio................................................................................. 123 Web Client Demo ........................................................................................................... 125 Lab 4A ............................................................................................................................ 128 Lab 4B............................................................................................................................. 129 Summary ......................................................................................................................... 130

Chapter 5: ASP.NET Web Services Programming Model ........................................... 135 Asynchronous Programming in Web Services ............................................................... 137 Example – Asynchronous Call........................................................................................ 138 Begin and End Asynchronous Methods.......................................................................... 140 Using a Callback Delegate.............................................................................................. 142 Example – Asynch Concatenate ..................................................................................... 144 Asynchronous Events in .NET 2.0.................................................................................. 145 Lab 5A ............................................................................................................................ 146 State Management in ASP.NET ..................................................................................... 147 Application and Session Objects .................................................................................... 148 Session Management ...................................................................................................... 149 Application Management................................................................................................ 150 Example – StateService .................................................................................................. 151 ASP.NET Web Services Transactions............................................................................ 153 Caching: An Overview ................................................................................................... 155 Data to be Cached – Time Frame ................................................................................... 156 Output Caching ............................................................................................................... 157 Output Caching Example................................................................................................ 158 Debugging....................................................................................................................... 159 Debugging a Web Service .............................................................................................. 160 Enable Debugging in Web.config................................................................................... 161 Deploying a Web Service ............................................................................................... 163 Lab 5B............................................................................................................................. 166 Summary ......................................................................................................................... 167

Chapter 6 XML Serialization ........................................................................................ 175 Serialization in .NET ...................................................................................................... 177 Serialization Demonstration ........................................................................................... 178 CLR Serialization ........................................................................................................... 179 Circular List and XML Serialization .............................................................................. 182 XML Serialization Demo................................................................................................ 183 XML Serialization Infrastructure.................................................................................... 188 What Will Not Be Serialized .......................................................................................... 189 XML Schema .................................................................................................................. 190 XSD Tool ........................................................................................................................ 191 A Sample Schema ........................................................................................................... 192 A More Complex Schema............................................................................................... 193 A Car Dealership ............................................................................................................ 194 Deserializing According to a Schema............................................................................. 195

Page 8: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC viii All Rights Reserved

Sample Program.............................................................................................................. 196 Type Infidelity ................................................................................................................ 197 Example – Serializing an Array...................................................................................... 198 Example – Serializing an ArrayList................................................................................ 201 Customizing XML Serialization..................................................................................... 203 Lab 6A ............................................................................................................................ 204 XML Serialization and Web Services ............................................................................ 205 ArrayList Web Service Example .................................................................................... 206 Lab 6B............................................................................................................................. 207 Summary ......................................................................................................................... 208

Chapter 7: More about SOAP ......................................................................................... 215 The SOAP Messaging Model ......................................................................................... 217 SOAP Namespaces ......................................................................................................... 218 The SOAP Envelope ....................................................................................................... 219 The Message Header....................................................................................................... 220 Using SOAP Headers in .NET........................................................................................ 221 Using SOAP Headers on the Client ................................................................................ 223 SOAP Header Example................................................................................................... 224 Call Body ........................................................................................................................ 226 Response Body................................................................................................................ 227 Lab 7A ............................................................................................................................ 228 Returning Errors ............................................................................................................. 229 Example – SOAP Fault ................................................................................................... 230 Document Style Web Services........................................................................................ 231 Document vs. RPC Style................................................................................................. 232 Wrapped vs. Bare Parameter Style ................................................................................. 233 Literal vs. Encoded Use .................................................................................................. 234 Example – Bare Document Style.................................................................................... 235 More Document Style Examples .................................................................................... 237 RPC Style Examples ....................................................................................................... 238 SOAP 1.2 ........................................................................................................................ 239 Specifying the Transport Protocols................................................................................. 240 Making a Request Using SOAP 1.2................................................................................ 241 Lab 7B............................................................................................................................. 242 Summary ......................................................................................................................... 243

Chapter 8: More about WSDL ........................................................................................ 251 SOAP-Based Web Services ............................................................................................ 253 Component-Based Software ........................................................................................... 254 Component Models......................................................................................................... 255 Web Services as Components......................................................................................... 256 A World without Type Information................................................................................ 257 The Need for Service Description .................................................................................. 258 An IDL for Web Services ............................................................................................... 259 Web Services Description Language.............................................................................. 260

Page 9: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC ix All Rights Reserved

WSDL Namespaces ........................................................................................................ 261 The WSDL Description Model....................................................................................... 262 Example – A WSDL Document...................................................................................... 263 A Bird’s Eye View.......................................................................................................... 264 WSDL Descriptors as Schema........................................................................................ 265 The Schema for WSDL Descriptors ............................................................................... 266 Associations between Components ................................................................................ 267 Interface Description....................................................................................................... 268 Messaging Scenarios....................................................................................................... 269 Operations: Input, Output, and Fault ............................................................................. 270 Messages ......................................................................................................................... 271 Example – Complex Types............................................................................................. 272 Service Description......................................................................................................... 274 Extending WSDL............................................................................................................ 275 The Binding Component................................................................................................. 276 A Structural Pattern ........................................................................................................ 277 The SOAP Binding ......................................................................................................... 278 Example – Binding for RpcMath.................................................................................... 279 Document vs. RPC Style................................................................................................. 282 Encoded vs. Literal Use .................................................................................................. 283 Lab 8A ............................................................................................................................ 284 Using WSDL Files.......................................................................................................... 285 An Abstract Class ........................................................................................................... 286 Implementing the Web Service....................................................................................... 287 WSDL First!.................................................................................................................... 288 WSDL Support in .NET.................................................................................................. 290 WSDL Viewer Tool ........................................................................................................ 291 WSDL Viewer Source Code........................................................................................... 292 Lab 8B............................................................................................................................. 294 Summary ......................................................................................................................... 295

Chapter 9: Data Access with Web Services.................................................................... 299 Multiple-Project Solutions.............................................................................................. 301 Demo: A Two-Project Solution ...................................................................................... 302 A Windows Application Client Project .......................................................................... 304 Adding a Web Reference ................................................................................................ 306 Multiple Projects in Solution Explorer ........................................................................... 307 Implementing the Client ................................................................................................. 308 Lab 9A ............................................................................................................................ 309 Multiple-Tier Data Access.............................................................................................. 310 Sample Database............................................................................................................. 311 Data Access Example ..................................................................................................... 312 Data Access Demo.......................................................................................................... 314 A Data Access Web Service ........................................................................................... 322 Data Access Client Code ................................................................................................ 325 An Enhanced Web Service ............................................................................................. 327

Page 10: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC x All Rights Reserved

Client for Enhanced Web Service................................................................................... 330 Objects in a ListBox ....................................................................................................... 331 Web Services Pass Data.................................................................................................. 332 LocalCourse .................................................................................................................... 333 Client Code ..................................................................................................................... 334 Type Information in Web Services ................................................................................. 336 TypedDataDemo Example.............................................................................................. 337 Type Information as XML Schema ................................................................................ 338 Typed DataSets in Web Services.................................................................................... 339 Adding a Typed DataSet................................................................................................. 340 Returning a Typed DataTable......................................................................................... 342 Binding to a Web Service ............................................................................................... 343 Troubleshooting Tip ....................................................................................................... 347 Lab 9B............................................................................................................................. 348 Summary ......................................................................................................................... 349

Chapter 10: Introduction to WCF .................................................................................. 357 What Is WCF?................................................................................................................. 359 WCF Services ................................................................................................................. 360 Service Orientation ......................................................................................................... 362 WCF and Web Services .................................................................................................. 363 WCF = ABC ................................................................................................................... 364 Address, Binding, Contract............................................................................................. 365 Example – Echo Service ................................................................................................. 366 Hosting Services ............................................................................................................. 367 Demo – Echo Service...................................................................................................... 368 A Website for the Service ............................................................................................... 369 Service Configuration ..................................................................................................... 372 Configuration Details...................................................................................................... 373 Examining the Service in the Browser ........................................................................... 374 WCF Clients.................................................................................................................... 375 Creating WCF Clients..................................................................................................... 376 Demo – A Client for Echo Service ................................................................................. 377 Add Service Reference Dialog ....................................................................................... 379 Lab 10A .......................................................................................................................... 382 Interop with ASMX Web Services ................................................................................. 383 Interop Demonstration .................................................................................................... 384 EchoService20 ................................................................................................................ 385 EchoServiceASMX......................................................................................................... 386 .NET 2.0 Client ............................................................................................................... 387 EchoService .................................................................................................................... 388 EchoClient35 Code ......................................................................................................... 389 Data Contracts................................................................................................................. 390 Data Contract Example ................................................................................................... 391 Operation Contract.......................................................................................................... 392 Client Program................................................................................................................ 393

Page 11: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC xi All Rights Reserved

Deploying a WCF Web Service...................................................................................... 394 Deployment Demo .......................................................................................................... 395 Lab 10B........................................................................................................................... 402 Summary ......................................................................................................................... 403

Appendix A: Learning Resources.................................................................................... 411

Appendix B: Configuring IIS for ASP.NET................................................................... 415 ASP.NET Versions Side-by-Side ................................................................................... 416 Configuring for ASP.NET 2.0 ........................................................................................ 417 Installing ASP.NET ........................................................................................................ 420

Page 12: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

Rev. 3.0 Copyright ©2009 Object Innovations Enterprises, LLC xii All Rights Reserved

Page 13: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

What Are Web Services?

Page 14: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 2 All Rights Reserved

What Are Web Services?

Objectives

After completing this unit you will be able to:

• Answer the questions “What are Web services?” and “What is the need for Web services?”

• Illustrate how Web services are different from present distributed technologies.

• Provide examples of the different benefits of Web services.

• Outline the baseline Web services specifications of XML, SOAP, WSDL and UDDI.

• Identify the major players who are shaping the Web services architecture for the industry.

• Describe some business models for Web services.

• Discuss Service Oriented Architecture (SOA) and the use of Web services for its implementation.

• Discuss ASP.NET as a technology for implementing Web services and other .NET alternatives to Web services.

Page 15: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 3 All Rights Reserved

What is a Web Service?

• A Web service is an XML message delivered over some transport mechanism.

− HTTP has been the most common transport.

− SOAP has become the industry standard message format.

• The producer of the Web service maps an object, service, program or database to the XML message.

• The consumer of the Web service maps the XML message to an object, service, program, or database.

• A Web service is executed via the application that consumes it.

Page 16: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 4 All Rights Reserved

Why are Web Services Needed?

• Web services provide a neutral means to integrate programs built on different development platforms.

− Web services are superior to distributed object technologies.

• Web services provide a means to evolve applications as customer requirements change.

− Web services enable applications built with a Service Oriented Architecture (SOA).

• Let us examine each of these in more detail.

Page 17: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 5 All Rights Reserved

Distributed Object Computing

• Building scalable solutions require applying the appropriate level of computing power to different parts of the application.

• Distributed object computing extends an object-oriented programming system by allowing objects to coexist across a heterogeneous network and interact as if they resided on the same machine.

• In the early 1990’s many companies including Microsoft, Sun Microsystems, the Object Management Group and IBM recognized the need of distributed computing and developed their own technologies to facilitate communication among distributed components.

− Microsoft’s DCOM (Distributed Component Object Model)

− Sun Microsystems’ RMI (Remote Method Invocations)

− Object Management Group’s CORBA (Common Object Request Broker Architecture)

− IBM’s DSOM (Distributed System Object Model)

• Distributed object systems have several problems.

Page 18: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 6 All Rights Reserved

OOP and Network Latency

• The style of object-oriented programming directly conflicts with the performance of distributed systems.

− Object-oriented classes are fine grained, with property and field accessors.

− Object interactions lead to many round trips across the network. Network latency causes severe performance degradation. You want to minimize the number of interactions between client and server.

class Store { public string Name(){get;set} public string Location() {get;set} public string Hours(){get;set} public void CreateStore(); public void SaveStore(); }

• Distributed systems require “chunky” rather than “chatty” interfaces between the distributed pieces.

− Such interfaces have methods that transfer larger quantities of data.

class Store { public void CreateStore(string name, string location, string hours); public void SaveStore(string name, string location, string hours); }

Page 19: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 7 All Rights Reserved

Object State and Scalability

• Scalability is the performance of the system under increased load.

− Systems are scalable if performance can be increased by just adding hardware.

• Object-oriented systems tend to have many fine-grained objects.

− Keeping these objects alive consumes resources that prevent servicing more requests.

• Tracking distributed object lifetimes across the network so that objects can release their proxies, increases network traffic, and degrades performance.

• Persistent distributed objects also interfere with load balancing to distribute processing evenly among computers.

− Stateless objects can be created or destroyed between method calls. State is stored in the non-distributed part of the application.

− For example, an object that holds on to a database connection interferes with scalability.

Page 20: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 8 All Rights Reserved

Interoperability

• Each distributed object system used its own transport mechanism.

− The various distributed object systems of the different vendors did not interoperate.

− Although in principle CORBA was a vendor-neutral specification, in practice customers were locked into their particular choice of vendor implementation.

• The various distributed object systems used different wire protocols.

− This is similar to having different procedure calling conventions between method calls.

• The various distributed object systems require keeping non-standard Internet ports open for remote object invocation.

− These protocols are not transparent to the usual settings for firewalls.

Page 21: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 9 All Rights Reserved

Industry Standard Messaging

• HTTP is a ubiquitous transport standard.

− Port 80 is almost always open on a firewall.

• Since HTTP is a text-based protocol, XML was a natural choice for implementing an object-neutral messaging protocol.

• By exchanging messages instead of object method calls, applications built with different object models, and different implementation technologies can interact.

• Messaging technologies are more robust and scale better in distributed scenarios.

• This looser coupling, however, makes it harder for type information and transactional context to be transmitted.

• SOAP and WSDL have emerged as the fundamental specifications for Web services.

• Additional specifications such as WS-Security and WS-Addressing are designed to solve some additional issues associated with Web services.

• Future standards such as WS-Eventing (for publish and subscribe) will impact application development.

Page 22: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 10 All Rights Reserved

Major Players in Web Services

• The major players deeply involved and invested in Web services are Microsoft, IBM, Sun Microsystems, Oracle, and many other companies.

− IBM, Microsoft, and BEA have been the originating forces behind the two key Web service specifications, SOAP and WSDL.

− The World Wide Web Consortium, or W3C, controls some key Web services specifications as XML and XML Schema.

− W3C has approved SOAP 1.2 as a recommendation. SOAP 1.1 and 1.0 are W3C notes.

− WSDL 1.1 is a W3C note, not a recommendation. WSDL 2.0 is currently a W3C Candidate Recommendation (January 6, 2006).

− The IETF (Internet Engineering Task Force) originally specified the Hypertext Transfer Protocol, or HTTP. This is now managed jointly with the W3C.

− Other specifications such as WS-Security were developed under the aegis of the OASIS consortium.

− Thus far, the Web services initiative is unique among distributed-computing standards efforts in that it operates under no single authority.

− The organization works across the industry and standards organizations to respond to customer needs by providing guidance, best practices, and resources for developing Web services solutions.

Page 23: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 11 All Rights Reserved

Web Services Interoperability

• Given the various specifications and their revisions it is necessary to define levels of interoperability.

− For example, SOAP 1.0, 1.1, and 1.2 systems exist, and not everything is backward compatible.

− The current WSDL specification has some ambiguities. WSDL 2.0 is not a recommendation yet.

− WS-Security is a newly approved specification, and not supported everywhere yet.

• The Web Services Interoperability Organization (WS-I) is an open, industry organization chartered to promote Web services interoperability by defining levels of compliance.

• The Basic Profile 1.1 defines a set of guidelines for minimal interoperability of Web services.

− In addition the major vendors have created reference implementations that correspond to the Basic Profile 1.1.

Page 24: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 12 All Rights Reserved

Benefits of Web Service Integration

• Let’s look at some business advantages of Web services.

− Web services offer new business opportunities by making it easy to connect with partners. (Business to Business Integration).

− Reduce application development and maintenance costs. (Save time and money).

− Create new sources of revenue by making the present useful functionality into Web services.

− Web services provide a solution to systems interoperability problems.

− Implement cross-platform, program-to-program communications (application integration).

− Deliver significantly more personal, integrated experiences to users using Web services.

− Web services connect information, applications, people, systems and devices.

Page 25: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 13 All Rights Reserved

SOAP

• SOAP (Simple Object Access Protocol) is a lightweight protocol for the exchange of information in a decentralized, distributed environment.

− SOAP is a protocol that defines how to send messages in a platform-independent manner using XML.

− SOAP, the Simple Object Access Protocol, uses XML as a wire protocol to describe how the data and its associated type definitions are transmitted.

− SOAP was developed by Microsoft, IBM and others, and then hand over to the W3C for further development.

Page 26: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 14 All Rights Reserved

WSDL

• The WSDL (Web Service Description Language) is an XML-based grammar for describing the syntax of Web services, their functions, parameters, and return values.

− WSDL defines the methods and the data associated with a Web service.

− Since WSDL is XML-based, it is both human and machine readable. However WSDL is designed to be used by machines for automated implementation of interface contracts.

• WSDL can be thought of as the IDL of Web Services.

WSDL Section Use

Types Defines types

Messages Abstract message signature

Operations Abstract method definition

Port Type Abstract interface based on operations

Binding Interface and method implementation

Port Associates binding with a specific address (instantiated object)

Service Collection of ports (component: is a collection of instantiated objects)

Page 27: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 15 All Rights Reserved

UDDI

• The UDDI (Universal Description, Discovery, and Integration) specification defines a SOAP-based Web service for locating WSDL-formatted protocol descriptions of Web services

− It is the standard way to publish and discover information about Web services).

• UDDI is a business registry which allows businesses and developers to programmatically locate information about Web services exposed by other organizations.

− At present, UDDI is not a standard, but is a joint initiative of businesses and vendors.

− The latest UDDI Version 3 has some unique features such as multi-registry topologies, increased security features, improved WSDL support, a new subscription API and core information model advances.

Page 28: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 16 All Rights Reserved

Web Services Business Models

• Many companies are using XML Web services to improve the way they do business, cut development costs, and increase customer satisfaction.

− Web services are a powerful business tool, allowing unprecedented customer integration and partnering opportunities.

− A lot of companies are espousing Web services to simplify internal business process and to distributing their services and products.

− Let us investigate some business models of Web services.

Page 29: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 17 All Rights Reserved

Business Models Classified

• B2C, or business-to-consumer, is a Web business catering to individual consumers.

− Amazon.com and eCommerce sites in general are classic examples.

• B2B, or business-to business, is a Web business catering to other businesses.

− Suppliers and vendors to manufacturing companies are examples of B2B businesses.

• Classic B2C and B2B have human interaction to Web pages.

• Web services facilitate two new models:

− S2C, or service-to-consumer, provides a programmatic interface to a consumer-type function.

− S2B, or service-to-business, provides a programmatic interface to a business-type function served by one business to another business.

Page 30: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 18 All Rights Reserved

Service Oriented Architecture (SOA)

• Objects do not always easily reflect real-world processes and relationships.

• Distributed object systems have trouble evolving to reflect the dynamic nature of customer requirements and businesses.

• Building applications out of services allows for a more flexible architecture in building complex applications, especially if the services are owned by different divisions, or even different businesses.

• Service orientation allows you to build applications out of new services, services cleaved out of old applications, or applications wrapped as services.

• SOA is important when applications have to cross trust boundaries.

• Object technology can be used in implementing services.

• Web services are the natural implementation technology for SOA.

Page 31: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 19 All Rights Reserved

Services Are Independent

• A service is composed of code and data.

− Completely separate from another services’ code and data.

• Services are connected through messaging.

− MQ Series technology has been around for a long time

− Messages are defined by contracts and XML Schema.

− The order of the message is part of the contract.

− Implementation is not part of the contract.

• Boundaries are explicit

− Code, data, database tables are either within or outside of the service, there is no sharing

− Database transactions are not shared among services.

− Failure isolation is mandatory.

• A service is deployed independently of other services.

• Service compatibility is based on policy.

− WS-Policy allows services to specify polices such as how authentication should be done.

− Policy is a set of assertions that a Service expects to be true.

• A Service is separate from the User Interface.

Page 32: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 20 All Rights Reserved

ASP.NET Web Services

• ASP.NET Web services are built on top of ASP.NET; therefore you can benefit from the features of ASP.NET to build Web services.

− Distinctively, ASP.NET not only takes advantage of performance enrichments found in the .NET Framework and the common language runtime, it has also been designed to offer significant performance improvements over ASP and other Web development platforms.

• ASP.NET Web services facilitate Web services’ accessing the many features of the .NET Framework, such as authentication, caching, tracing and state management.

− Developers can focus on creating or accessing Web services without needing to write infrastructure code, because ASP.NET and the .NET Framework are the foundation for Web services in managed code.

• Visual Studio 2008 is a complete set of development tools for building Web applications, Web services, desktop applications, and mobile applications.

− Therefore with the assistance of Visual Studio, you can quickly create, consume and deploy Web services.

Page 33: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 21 All Rights Reserved

Alternative Technologies

• Within the Microsoft platform, there are several alternative technologies to ASP.NET Web Services (asmx).

− ASP.NET Web Services is the best match to SOA because you get explicit service boundaries, and has the scalability features of ASP.NET.

• Web Service Enhancements (WSE) is designed to take advantage of leading edge Service Oriented Architecture technology for ASMX.

• .NET Remoting

− Distributed objects when both ends host the CLR.

− Works best for AppDomain to AppDomain communication within the same process.

− Can integrate with an existing proprietary protocol using extensibility features.

• Enterprise Services

− Need the features of COM+.

− Communicate with objects on local machine when you have performance issues with ASMX and WSE

• MSMSQ

− Asynchronous Messaging

Page 34: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 22 All Rights Reserved

Web Service Enhancements 3.0

• Web Service Enhancements (WSE) provides additional Web services support to the .NET Framework.

− The idea is to provide enhancements that are not tied to the .NET Frameworks release cycle.

− Since this is “bleeding edge” support, there is no guarantee of backwards compatibility as specifications and messaging frameworks evolve.

• WSE enhances Web services in three areas.

− Support for transports other than HTTP without using ASP.NET.

− Support for security specifications such as WS-Security, WS-Trust, WS-Policy, and WS-SecureConversation.

− Support for enhanced Web services such as DIME (Direct Internet Message Encapsulation) and WS-Routing.

• WSE is a transition technology and is now superseded by Windows Communications Foundation (WCF).

Page 35: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 23 All Rights Reserved

Windows Communication Foundation

• Windows Communication Foundation (WCF) is a new service-oriented programming framework for creating distributed applications.

− It was previously known as ‘Indigo’ and is part of .NET 3.5.

• WCF is designed to provide one mechanism for building connected applications:

− Within app domains

− Across app domains

− Across machines

• WCF builds upon and extends existing ways of building distributed applications:

− ASMX Web services, .NET Remoting, COM, MSMQ.

• All these do the same basic job (connecting elements in distributed applications) but they are very different at the programming level, with complex APIs and interactions.

− WCF provides one model for programming distributed applications. Developers only need to learn one API.

• WCF leverages existing mechanisms.

− It uses TCP, HTTP and MSMQ for transport.

Page 36: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 1

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 24 All Rights Reserved

Summary

• Web services are used to implement a distributed computing architecture.

• Web services provide some application logic, and are available to any number of potentially dissimilar systems through the use of standards, such as SOAP, XML and HTTP.

• WSDL is used for describing the Web services, and UDDI provides a registry service for publishing and locating Web services.

• Web services trim down development cost and maintenance cost, and provide a solution to interoperability issues.

• Web services can create new business opportunities and used in various businesses models such as S2C and S2B scenarios.

• Service Oriented Architecture (SOA) is the future of enterprise application architecture, and ASP.NET Web Service is an effective current Microsoft technology match for implementation.

• Windows Communications Foundation (WCF) is the newest Microsoft technology for implementing SOA.

Page 37: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 113 All Rights Reserved

Chapter 4

Web Service Clients

Page 38: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 114 All Rights Reserved

Web Service Clients

Objectives

After completing this unit you will be able to:

• Explain the concept of a Web service proxy.

• Create proxies for different protocols using the wsdl.exe utility.

• Understand the generated proxy code.

• Use Visual Studio to automatically generate a proxy by adding a Web reference to your project.

• Develop Windows Form and Web Form clients for Web services.

Page 39: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 115 All Rights Reserved

Protocols

• A client application can use the following three protocols to consume a Web service created by ASP.NET:

− HTTP-GET

− HTTP-POST

− SOAP (versions 1.1 and 1.2)

• An ASP.NET Web service can support clients using the SOAP, HTTP-GET, and HTTP-POST protocols to invoke Web service methods.

− In HTTP GET the data is sent in the query string (name/value pairs) that is appended to the URL.

− In HTTP POST the data is not appended to the query string as in HTTP GET, but instead name/value pairs are written in the HTTP body (which appears after the HTTP header, with a blank line separating the header and body), and the data is not directly visible to the outside world.

− The supported data types for HTTP GET/POST are string (for Int16, Int32, Int64, Boolean, Single, Double, Decimal, DateTime, etc), enumerations and simple arrays. (NOTE: Even though it uses HTTP GET/POST, the browser test form supports only simple data types, no arrays.)

− You cannot make use of HTTP GET/POST to represent some complex data types such as object instances, ADO.NET Datasets, XML nodes and complex arrays. However SOAP supports a richer set of data types, as mentioned previously.

Page 40: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 116 All Rights Reserved

Accessing a Web Service

• There are two primary steps when working with Web services:

− Creating a Web service and accessing a Web service

• Till now we discussed how to create a Web service and test in the IE test page. Let us explore how to develop a console app, Windows Form or Web Form client.

− In consuming a Web service, the client application has to locate, reference, and invoke the functionality in a Web service.

− Now let us create clients for some of the Web services we previously implemented.

• The fundamental steps in consuming Web services are as follows:

− Create a proxy class for the Web service, either manually or generate one by using the wsdl.exe tool or by adding a Web reference to your project.

− When using Visual Studio, add the proxy class created manually or by WSDL.exe to your project.

− In the client code, reference the proxy class by adding its required namespace.

− Create an instance of the proxy class and invoke the Web service methods using that proxy.

Page 41: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 117 All Rights Reserved

Creating a Proxy

• A proxy class acts as an intermediary between a Web service and the client.

− The proxy class transmits the required arguments from client to the Web service and also it takes care in return of the result back to client.

• Web service Proxy Client

− By default, the proxy class uses SOAP to access the Web service method.

• Creating a proxy class could be done manually, using the .NET Framework API, but it is much easier to use a tool:

− Generate a proxy using the wsdl.exe command line tool.

− Generate a proxy with Visual Studio by adding a Web reference to your project.

• Let’s use both techniques for developing clients.

− ConcatenateClient for a console client of Concatenate with proxy generated via wsdl.exe.

− WebClient for a Web Forms client of Concatenate with the proxy generated by adding a Web reference.

Page 42: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 118 All Rights Reserved

Creating a Proxy using wsdl.exe

• The wsdl.exe command line tool is used to create a proxy class with the help of WSDL file.

• You have to specify the name of the proxy file to be created and the URL where the service description is available as follows.

wsdl /l:C# /out:concatproxy.cs /protocol:SOAP http://localhost/WsNetCs/Chap03/Concatenate/ Concatenate.asmx?WSDL

− In ConcatenateClient folder you can run the wsdlbuild.bat batch file.

− The wsdl tool creates C# proxy class by default. For other languages like Visual Basic (vb) or JScript .NET (js), you can use the optional /l: language flag.

− The full syntax for the wsdl.exe tool is as follows

wsdl /language:language /protocol:protocol /namespace:myNameSpace /out:filename /username:username /password:password /domain:domain <url or path>

− You can see a listing of all the flags of the wsdl.exe utility by simply typing wsdl in the command prompt.

Page 43: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 119 All Rights Reserved

Exploring the Generated Proxy Code

• The generated concatproxy.cs file contains a proxy class exposing both synchronous and asynchronous methods for each Web service method of the Web service.

using System; using System.ComponentModel; using System.Diagnostics; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Serialization; ... [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute( Name="ConcatenationSoap", Namespace="http://oi.com/")] public partial class Concatenation : System.Web.Services.Protocols.SoapHttpClientProtocol { ... public Concatenation() { this.Url = "http://localhost/WsNetCs/Chap03/Concatenate/Concatenate.asmx"; } ...

Page 44: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 120 All Rights Reserved

Generated Proxy Code (Cont’d)

System.Web.Services.Protocols.SoapDocumentMethodAttribute( "http://oi.com/Concatenate", RequestNamespace="http://oi.com/", ResponseNamespace="http://oi.com/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle= System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string Concatenate(string s1, string s2) { object[] results = this.Invoke("Concatenate", new object[] { s1, s2}); return ((string)(results[0])); } /// <remarks/> public System.IAsyncResult BeginConcatenate(string s1, string s2, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("Concatenate", new object[] { s1, s2}, callback, asyncState); } /// <remarks/> public string EndConcatenate( System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string)(results[0])); }

Page 45: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 121 All Rights Reserved

Generated Proxy code (Cont’d)

• Let us explore the generated proxy class.

− You can observe that the constructor of the proxy class initializes the URL of the Web service.

• If you investigate the generated proxy class, it has three methods, namely Concatenate(), BeginConcatenate(), and EndConcatenate()

− The Concatenate() method of the proxy class is used to call the Concatenate Web service method synchronously.

− BeginConcatenate() and EndConcatenate() can be used to call a Web service asynchronously.

• Return results are cast appropriately.

• You can also identify that the proxy class generated derives from the SoapHttpClientProtocol class, which derives from the abstract WebClientProtocol class.

Page 46: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 122 All Rights Reserved

Console Client Test Program

• The console client test program has two source files and has references to three assemblies.

− See ConcatenateClient

• Here is the client source code: using System; public class ConcatenateClient { public static void Main() { Concatenation cat = new Concatenation(); string s = cat.Concatenate("spider-", "man"); Console.WriteLine(s); } }

• Here is the output (make sure that you have Chap03/Concatenate set as an IIS application):

spider-man

Page 47: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 123 All Rights Reserved

Creating a Proxy via Visual Studio

• It is easy to create a proxy using Visual Studio 2008.

− The only shortcoming when you use Visual Studio is that you can specify the protocol as SOAP only. But you can specify the protocol as HttpGet, HttpPost or SOAP in the wsdl.exe utility using the /protocol flag.

• As a demo let’s create a Web Forms client for our Concatenate Web service.

− In a lab you will create a Windows Forms client for another Web service.

− Do your work in the Demos directory.

• In this part of the course we’re going to target .NET Framework 2.0.

− We will then see a menu item for Add Web Reference in Visual Studio’s Website menu and in the context menu brought up by right-clicking on the project in Solution Explorer.

• If our new website targets .NET Framework 3.5, we’ll see an Add Service Reference menu item instead.

− This menu item will enable us to add a Service Reference to a WCF Service and, through an Advanced button, a Web Reference to an ASP.NET Web Service.

− See Chapter 10.

Page 48: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 124 All Rights Reserved

Web Client Demo (Cont’d)

1. Create a new Visual Studio ASP.NET Web Site WebClient. Select target .NET Framework 2.0 and location File System.

2. Create a user interface as shown (be sure to select from the Toolbox’s Standard controls, not its HTML controls):

Page 49: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 125 All Rights Reserved

Web Client Demo

3. Change the names of the controls to txtString1, txtString2, lblResult and btnConcatenate.

4. In Solution Explorer, right-click on your project and choose Add Web Reference. In the dialog that comes up, enter the location of the Concatenate Web service (or browse to it):

http://localhost/WsNetCs/Chap03/Concatenate/ Concatenate.asmx

5. Press Enter (or click the “Go” button). You should see a page on the Concatenation Web service. Click Add Reference.

Page 50: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 126 All Rights Reserved

Web Client Demo (Cont’d)

6. In Solution Explorer you will now see that an ASP.NET folder App_WebReferences has been added to your project.

7. You will not find any generated proxy code. It will be generated on the fly. (This is for ASP.NET applications. In other cases, you will find generated code in a file Reference.cs.) To access the proxy you will need the namespace localhost.

8. Double-click on the Concatenate button to add a command handler, and add the following code. Build and run.

using localhost; ... protected void btnConcatenate_Click(object sender, EventArgs e) { string s1 = txtString1.Text; string s2 = txtString2.Text; Concatenation cat = new Concatenation(); lblResult.Text = cat.Concatenate(s1, s2); }

Page 51: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 127 All Rights Reserved

Web Client Demo (Cont’d)

9. Enter some test data and click the Concatenate button.

10. Note that for the Web Form we are going through the ASP.NET Development Server, and for the Web service we are going through IIS. You can find information about the connection to the Web service in the <appSettings> section of the Web.config file that is generated when you add a Web Reference. Note that the URL specified here overrides that in the code.

<configuration> <appSettings> <add key="localhost.Concatenate" value="http://localhost/WsNetCs/Chap03/ Concatenate/Concatenate.asmx"/> </appSettings> ...

Page 52: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 128 All Rights Reserved

Lab 4A

A Client for Array Sort Web Service

In this lab you will create a Windows client for the Sort Web service you created in Lab 3B. You will use the same user interface previously employed to test the sort DLL.

Detailed instructions are contained in the Lab 4A write-up at the end of the chapter. Suggested time: 20 minutes

Page 53: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 129 All Rights Reserved

Lab 4B

Creating a Proxy using wsdl.exe

In this lab you will create a Windows client program for the Math Web service from Chapter 3, using the wsdl.exe tool to create a proxy. If you have extra time, you can create another version of the client using Add Web Reference in Visual Studio, gaining some added practice.

Detailed instructions are contained in the Lab 4B write-up at the end of the chapter. Suggested time: 20 minutes

Page 54: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 130 All Rights Reserved

Summary

• A proxy class acts as an intermediary between a Web service and the client.

• The proxy class derives from SoapHttpClientProtocol, and suitable attributes must be supplied to the class and to the methods.

• To generate a proxy class you can use either the Visual Studio Add Web Reference dialog box or the wsdl.exe utility.

• Web services support both synchronous and asynchronous communication between the client and the service.

• Under synchronous communication, the client sends a request for a service to the service and waits for the response.

• Asynchronous programming and other topics are discussed in detail in the upcoming chapters.

Page 55: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 131 All Rights Reserved

Lab 4A

A Client for Array Sort Web Service

Introduction In this lab you will create a Windows client for the Sort Web service you created in Lab 3B. You will use the same user interface previously employed to test the sort DLL.

Suggested Time: 20 minutes Root Directory: OIC\WsNetCs Directories: Labs\Lab4A\SortServiceClient (starter code)

Chap03\SortLibClient\Step2 (backup of starter code) Chap04\SortServiceClient (answer) Chap03\SortService\SortService (Sort Web service)

Instructions: 1. Change the name of the project file to SortServiceClient.csproj. Delete the .sln file,

and open up the project. Change the name of the assembly and default namespace to SortServiceClient (right-click on the project and choose Properties from the context menu.) Build. You will then be prompted to save the solution under the name SortServiceClient.sln. Do so. Run the program. You should notice almost zero latency in calling the various sorts, because the call is going to a local DLL.

2. Change the caption of the form to “Sort Web Service Client.”

3. Delete the reference to SortLib and delete the file SortLib.dll.

4. Make sure that the SortService from Chapter 3 is configured in IIS as an application. Bring up the browser test page. You will see a list of operation, although you will not be able to actually exercise them, because of the complex data types that are passed.

Page 56: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 132 All Rights Reserved

Copy the URL http://localhost/WsNetCs/Chap03/SortService/SortService.asmx (from the Properties window) into the clipboard.

5. Back in the SortServiceClient project, add a Web Reference. Paste the URL you copied from the preceding step (or browse to the Web service) and press Enter or click Go.

6. In Form1.cs, modify the using statement for the SortLib namespace to use the namespace of the proxy, which is localhost.

7. Replace the code in each button handler to call through the Web service proxy in place of through a local DLL. Build and run. You should see the same behavior as before, but there may be some latency in calling a Web service for the first time.

Page 57: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 133 All Rights Reserved

Lab 4B

Creating a Proxy using wsdl.exe

Introduction In this lab you will create a Windows client program for the Math Web service from Chapter 3, using the wsdl.exe tool to create a proxy. If you have extra time, you can create another version of the client using Add Web Reference in Visual Studio, gaining some added practice.

Suggested Time: 20 minutes Root Directory: OIC\WsNetCs Directories: Labs\Lab4B\MathClient (starter code)

Chap04\MathClient\Starter (backup of starter code) Chap04\MathClient\Wsdl (answer) Chap04\MathClient\WebReference (answer to optional exercise) Chap03\MathService\MathService (Math Web service)

Instructions: 1. Make sure that MathService from Chapter 3 is configured in IIS as an application.

2. Build and run the starter program. You will just see the user interface displayed.

3. Open up the Visual Studio 2008 command prompt. Navigate to the Labs\Lab4B\MathClient directory.

4. Generate a proxy by using the command:

wsdl /l:C# http://localhost/WsNetCs/Chap03/MathService/ MathService.asmx?WSDL

Page 58: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 4

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 134 All Rights Reserved

5. Add the generated proxy file MathService.cs to your project, and examine the code

to see how to call methods of the proxy.

6. Add a reference to System.Web.Services.

7. Add handlers for the three buttons.

8. Implement a handler for the Add button by performing the following steps:

a. Instantiate a MathService proxy object.

b. Convert the contents of the textboxes for X and Y to integers.

c. Invoke the Add method through the proxy to determine the integer answer.

d. Display the answer in the answer textbox.

9. In a similar manner implement handlers for the Divide and Add Float buttons.

10. Build and test.

11. If you have some extra time, delete MathService.cs from your project and create a proxy in Visual Studio 2008 by using the Add Web Reference technique. Modify your code to use this proxy instead.

Page 59: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 215 All Rights Reserved

Chapter 7

More about SOAP

Page 60: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 216 All Rights Reserved

More about SOAP

Objectives

After completing this unit you will be able to:

• Describe the structure of SOAP messages.

• Use SOAP headers for passing information in SOAP messages.

• Describe SOAP faults and program SOAP faults using .NET exception handling.

• Explain the differences between document and RPC styles of Web services.

• Explain the difference between literal and encoded Web method calls.

• Use attributes to shape the body of a SOAP message.

• Use both SOAP 1.1 and SOAP 1.2 in ASP.NET Web services and Web services clients.

Page 61: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 217 All Rights Reserved

The SOAP Messaging Model

• A SOAP message travels as the payload of some other protocol; from there the SOAP specification defines a hierarchical model for message content.

• The SOAP message fundamentally consists of a single XML element called the SOAP envelope. This in turn includes:

− The SOAP header, which can include peripheral information that affects the processing of the message

− The SOAP body, with the core message content

• Attachments are supported outside the SOAP envelope; SOAP relies on the transport protocol to manage these.

Page 62: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 218 All Rights Reserved

SOAP Namespaces

• The SOAP 1.1 specification defines two namespaces for use in all SOAP messaging:

− The “SOAP envelope” namespace defines types for the SOAP messaging model, including what we’ve just seen and some additional details. The common prefixes are soap: and soap-env:, and the URI is:

http://schemas.xmlsoap.org/soap/envelope/

− The “SOAP encoding” namespace defines necessary types for the “Section 5” rules for data encoding in SOAP messages. (This encoding is discussed later in this chapter.) The common prefixes are soap-enc: and enc:, and the URI is:

http://schemas.xmlsoap.org/soap/encoding/

Page 63: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 219 All Rights Reserved

The SOAP Envelope

• The SOAP envelope is the root element of an XML fragment; its type is Envelope.

− This element generally defines namespace prefixes for the entire message, although this is not required.

− It also declares the data-encoding style for the message; more on this a bit later.

− The envelope element contains an optional Header element and a mandatory Body element.

• There is not much more to the SOAP envelope.

− The point of the envelope (and the rationale behind its name) is that it acts as a wrapper of sorts around the message content.

− It is the interface between the supporting protocol and XML, and as such acts to carry potentially complex XML information over a simple, trusted protocol such as HTTP or SMTP.

Page 64: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 220 All Rights Reserved

The Message Header

• The SOAP header is a single optional XML element placed as a child of the SOAP envelope.

• The header can hold any element or attribute content from non-SOAP namespaces.

• Each direct child of the header element is called a header entry.

• Headers are said to extend the SOAP model and also to extend a particular message’s semantics.

− Header entries are typically used to guide the process of message exchange, assuring that the core content gets to its intended destination appropriately.

− Header entries are more likely to be processed by an intermediary – a firewall, a message dispatcher, a resource manager – than by the ultimate destination of the message, which is likely a Web service.

− Some conventional header entries address common issues of messaging and distributed systems such as security, session management, and transaction control.

− Companies are free to define their own headers for their own uses, as well.

Page 65: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 221 All Rights Reserved

Using SOAP Headers in .NET

• The .NET Framework makes it easy to define and use SOAP headers.

• To specify and use a SOAP header in a Web service, do the following:

− Provide a using statement for the namespace System.Web.Services.Protocols.

− Define a class derived from SoapHeader to hold the information passed in the header (this example is from HeaderService).

public class EchoHeader : SoapHeader { public string UserName; public string LicenseKey; }

− In the Web service class declare a public instance of the header class.

public class HeaderService : System.Web.Services.WebService { ... public EchoHeader UserHeader;

Page 66: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 222 All Rights Reserved

Using SOAP Headers in .NET (Cont’d)

− Apply the [SoapHeader] attribute to methods that need to read information from the header

[WebMethod] [SoapHeader("UserHeader")] public string Reverse(string name) { ...

− You may then extract header information from the instance of the header class.

[WebMethod] [SoapHeader("UserHeader")] public string Reverse(string name) { if (UserHeader.LicenseKey == "0") return ReverseString(name); else return "Illegal license key"; }

Page 67: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 223 All Rights Reserved

Using SOAP Headers on the Client

• When you have created a Web service that processes SOAP headers, the generated proxy will then contain a class you can use for assigning information for the header (this example is from HeaderClient).

public class HeaderService : SoapHttpClientProtocol { public EchoHeader EchoHeaderValue; ... } public class EchoHeader : SoapHeader { /// <remarks/> public string UserName; /// <remarks/> public string LicenseKey; }

• You can then initialize the header with simple code like this:

header.UserName = txtUser.Text; header.LicenseKey = txtLicense.Text; proxy.EchoHeaderValue = header;

Page 68: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 224 All Rights Reserved

SOAP Header Example

• An Echo Web service utilizes a header containing a user name and a license key.

− The method Hello() creates a greeting string containing the user name from the header.

− The method Reverse() checks the value of a license key. If it is valid, it returns the reversed string, otherwise an error message. (The example assumes that “0” is the only valid license key.)

− The server is in the folder HeaderService and the client is in the folder HeaderClient\Step1.

Page 69: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 225 All Rights Reserved

SOAP Header Example

• The following SOAP request is submitted by the client:

POST /WsNetCs/Chap07/HeaderService/ HeaderService.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://oi.com/Reverse" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap= "http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <EchoHeader xmlns="http://oi.com/"> <UserName>Bob</UserName> <LicenseKey>0</LicenseKey> </EchoHeader> </soap:Header> <soap:Body> <Reverse xmlns="http://oi.com/"> <name>MISSISSIPPI</name> </Reverse> </soap:Body> </soap:Envelope>

Page 70: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 226 All Rights Reserved

Call Body

• The SOAP body of a call holds the fundamental message data, such as:

− The name of the method to invoke

− Arguments to pass to that method

<soap:Body> <Reverse xmlns="http://oi.com/"> <name>MISSISSIPPI</name> </Reverse> </soap:Body>

Page 71: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 227 All Rights Reserved

Response Body

• The SOAP body of a response holds return data (or fault information in the case of an error return).

− By convention, the response body’s first child element has the same name as the method name with a suffix of “Response”.

HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:soap= "http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <ReverseResponse xmlns="http://oi.com/"> <ReverseResult>string</ReverseResult> </ReverseResponse> </soap:Body> </soap:Envelope>

Page 72: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 228 All Rights Reserved

Lab 7A

Implementing a SOAP Header

In this lab you will implement the SOAP header example discussed in the chapter. A SOAP header is defined that contains a user name and a license key. You will implement both a Web service that reads the header and a corresponding client program that writes the header information.

Detailed instructions are contained in the Lab 7A write-up at the end of the chapter.

Suggested time: 40 minutes

Page 73: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 229 All Rights Reserved

Returning Errors

• Part of the SOAP specification covers handling errors.

• The basic mechanism in SOAP is the SOAP fault, which is part of the body of a response. Tags include:

− <soap:Fault>

− <faultcode>

− <faultstring>

− Optional <detail>

• The .NET Framework makes it easy to handle SOAP faults through the SoapException class.

− An exception on the server will cause the .NET Framework to create a SOAP fault to pass back.

− The proxy on the client will process a SOAP fault by throwing a SoapException, which can be caught by the client.

Page 74: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 230 All Rights Reserved

Example – SOAP Fault

• To illustrate SOAP fault handling, let’s make a small change to our HeaderService program.

− The server is FaultService and the client is FaultClient.

− In the Reverse method, throw an exception when an illegal license key is encountered. (This is an artificial example: you should not use exceptions for “normal” types of errors!)

[WebMethod] [SoapHeader("UserHeader")] public string Reverse(string name) { if (UserHeader.LicenseKey == "0") return ReverseString(name); else throw new Exception("Illegal license key"); }

− The .NET Framework will handle the exception by serializing fault information into the stream used for the response. The proxy will throw a SoapException.

Page 75: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 231 All Rights Reserved

Document Style Web Services

• It is tempting to think of Web services as simply a kind of RPC over the Web.

− Resist that temptation!

• The fundamental idea of Web services is message passing, not RPC.

− The messages that are passed are XML documents.

• Consider how SOAP could be used send to send information about a course and a customer.

− This could be an e-commerce application of a customer ordering a course, but at the protocol level it is simply an XML document that is being sent.

<?xml version="1.0" encoding="utf-8"?> <soap:Envelope <!-- various namespaces --> <soap:Body> <Course xmlns="http://WsNetCs"> <Id>501</Id> <Title>”Introduction to XML”</Title> <Price>50</Price> </Course> <Customer xmlns="http://WsNetCs"> <Name>”John Jones”</Name> <Email>”[email protected]”</Email> </Customer> </soap:Body> </soap:Envelope>

Page 76: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 232 All Rights Reserved

Document vs. RPC Style

• SOAP messages can be either document style or RPC style.

• The document style allows for arbitrary content under the SOAP body element.

− There can be multiple independent child elements directly underneath the body.

• In the RPC style the body will have a single child element identifying a method to be invoked, and this will have a child for each method parameter.

• In .NET you can specify a style for the Web service as a whole, and individual methods can have their own style overriding the style for the Web service.

• If no attributes are specified, the default is for document style.

• The document or RPC style is specified using attributes.

− Document style is specified by the [SoapDocumentService] attribute.

− RPC style is specified by the [SoapRpcService] attribute.

Page 77: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 233 All Rights Reserved

Wrapped vs. Bare Parameter Style

• Document-style SOAP has in turn two choices for how parameters are passed.

− In wrapped style, parameters sent to and from an XML Web service method are encapsulated within a single XML element within the body element of a SOAP message.

− In bare style, parameters sent to and from an XML Web service method are placed in XML elements within the body element of a SOAP message itself.

• The Course example we looked at previously is an example of the bare style.

• Bare style is permitted but not required for document-style SOAP.

− The bare option does not exist for RPC-style SOAP.

• The default parameter style for document-style SOAP is wrapped.

• Again attributes are used to specify the parameter style.

− ParameterStyle=SoapParameterStyle.Wrapped for wrapped.

− ParameterStyle=SoapParameterStyle.Bare for bare.

Page 78: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 234 All Rights Reserved

Literal vs. Encoded Use

• Information in SOAP messages can be formatted according to either of two standards:

− In literal use, message content is controlled directly by a schema, for instance an XML Schema.

− In encoded use, message content is governed by a set of encoding rules, which may incorporate one or more other schema but which set their own standards by which some types are encoded.

• Encoded use calls for additional information.

− The encoding rules must be identified, such as “SOAP Section 5” encoding.

• Document-style can have either literal or encoded usage.

− The default for document-style is literal.

• RPC-style can have only encoded usage.

• Once again attributes are used to specify use.

− Use=SoapBindingUse.Literal for literal.

− Use=SoapBindingUse.Encoded for encoded.

Page 79: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 235 All Rights Reserved

Example – Bare Document Style

• We can easily implement the style of SOAP message illustrated earlier in which the SOAP body had a Course element and a Customer element.

− See the SimpleCourse and CourseClient folders. The Web service logs to the file c:\OIC\Logs\log.txt, so you can verify that parameters are passed correctly.

• First, define corresponding .NET classes: // Course.cs public class CourseType { public int Id; public string Title; public decimal Price; } public class CustomerType { public string Name; public string Email; }

• Next, implement a .NET Web service as shown on the next page.

• Note the namespace required.

− The System.Web.Services.Protocols namespace consists of the classes that define the protocols used to transmit data across the wire. It is needed for the SoapDocumentMethod attribute.

Page 80: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 236 All Rights Reserved

Example – Bare Document Style

using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://oi.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.None)] public class SimpleCourse : System.Web.Services.WebService { [WebMethod] [SoapDocumentMethod( ParameterStyle = SoapParameterStyle.Bare)] public string Order(CourseType Course, CustomerType Customer) { Log.WriteLine("Order called"); Log.WriteLine("Course id = " + Course.Id); Log.WriteLine("title = " + Course.Title); Log.WriteLine("price = " + Course.Price); Log.WriteLine("Customer name = " + Customer.Name); Log.WriteLine("email = " + Customer.Email); return "OK"; } }

• Note that the bare document style does not conform to the WS-I Basic Profile.

Page 81: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 237 All Rights Reserved

More Document Style Examples

• There are four combinations of use and parameter styles that are applicable to document-style SOAP:

− Literal, wrapped (the default)

− Literal, bare

− Encoded, wrapped

− Encoded, bare

• The sample program DocMath illustrates all these combinations.

− Note the System.Web.Services.Description namespace that is required for the SoapBindingUse enumeration.

[WebMethod] [SoapDocumentMethod(Use=SoapBindingUse.Literal, ParameterStyle=SoapParameterStyle.Wrapped)] public int Add(int x, int y) { return x + y; } [WebMethod] [SoapDocumentMethod(Use=SoapBindingUse.Literal, ParameterStyle=SoapParameterStyle.Bare)] public int Subtract(int x, int y) { return x - y; } //etc.

Page 82: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 238 All Rights Reserved

RPC Style Examples

• RPC style implies both RPC use and wrapped parameter style. But there are a number of other customizations that can be performed (which could also be done with document style).

− Specify the SOAPAction.

− Specify the request and response namespaces.

− Specify the request and response element names. (For example, the convention for response element name is to append the suffix “Response”, but this can be overridden.)

• The RpcMath example illustrates a number of variations.

• The program MathClient tests both styles of SOAP messaging. The heavy lifting is done in the automatically generated proxy.

Page 83: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 239 All Rights Reserved

SOAP 1.2

• A noteworthy feature of .NET 2.0 is support for the SOAP 1.2 protocol.

− SOAP 1.2 is a W3C recommendation, as of June, 2003.

− But most current Web services still use SOAP 1.1.

• Web services created with .NET 2.0 are capable of communicating with both the 1.1 and 1.2 versions of SOAP.

• SOAP 1.2 has a different value for the Content-Type attribute in the HTTP header.

− Also, in SOAP 1.2 there is no SOAPAction attribute in the HTTP header, because this is combined with the Content-Type attribute.

POST /DocMath/DocMath.asmx HTTP/1.1 Host: localhost Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org... <soap12:Body> <Add xmlns="http://oi.com/"> <x>int</x> <y>int</y> </Add> </soap12:Body> </soap12:Envelope>

Page 84: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 240 All Rights Reserved

Specifying the Transport Protocols

• By default, a .NET 2.0 Web service can use the HTTP-POST, SOAP 1.1 and SOAP 1.2 protocols.

• You can add and remove protocol support via the Web.config file.

− For example, this adds support for HTTP-GET:

<configuration> <system.web> <webServices> <protocols> <add name ="HttpGet"/> </protocols> </webServices> </system.web> </configuration>

− And this removes support for SOAP 1.2:

<configuration> <system.web> <webServices> <protocols> <remove name ="HttpSoap12"/> </protocols> </webServices> </system.web> </configuration>

Page 85: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 241 All Rights Reserved

Making a Request Using SOAP 1.2

• By default, proxies in .NET 2.0 make use of the SOAP 1.1 protocol in requests to Web services.

• You can specify which SOAP version to use via the SoapVersion property of the Web services proxy object.

ws.SoapVersion = SoapProtocolVersion.Soap12;

− See the example program SoapClient\Step1 for an illustration of calling a Web service using either SOAP 1.1 or SOAP 1.2.

Page 86: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 242 All Rights Reserved

Lab 7B

Using SOAP 1.1 and SOAP 1.2

In this lab you will experiment with using either SOAP 1.1 or SOAP 1.2 in calling a Web service. You will implement a client program that can make a Web service request using either protocol. You will also experiment with the Web service by removing support for one or the other of the protocols.

Detailed instructions are contained in the Lab 7B write-up at the end of the chapter.

Suggested time: 20 minutes

Page 87: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 243 All Rights Reserved

Summary

• SOAP messages have an envelope with an optional header and a mandatory body.

• You can use SOAP headers for passing information in SOAP messages.

• Error handling in SOAP is done by SOAP faults, which are a section of the body of a response message.

• The document message style allows for arbitrary content under the SOAP body element.

• In the RPC style the body will have a single child element identifying a method to be invoked.

• Document-style SOAP permits both wrapped and bare styles for parameters.

• In literal use, message content is controlled directly by a schema, for instance an XML Schema.

• In encoded use, message content is governed by a set of encoding rules, such as SOAP Section 5.

• You can use attributes to shape the body of a SOAP message.

• .NET 2.0 supports both SOAP 1.1 and SOAP 1.2

Page 88: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 244 All Rights Reserved

Lab 7A

Implementing a SOAP Header

Introduction In this lab you will implement the SOAP header example discussed in the chapter. A SOAP header is defined that contains a user name and a license key. You will implement both a Web service and a corresponding client program that read and write the header information.

Suggested Time: 40 minutes Root Directory: OIC\WsNetCs Directories: Labs\Lab7A (do your work here) Chap07\HeaderService (server solution)

Chap07\HeaderClient\Step0 (client starter code backup) Chap07\HeaderClient\Step1 (client solution)

Part 1. Implement the Web Service 1. Use Visual Studio to create a new Web service project HeaderService. Rename the

.asmx file and corresponding class to HeaderService. Provide your own namespace in the WebService attribute.

2. In the “Hello World” code, change the method name to Hello. If you like, you may build and run at this point.

Page 89: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 245 All Rights Reserved

3. Define a class derived from SoapHeader to hold the information passed in the header.

public class EchoHeader : SoapHeader { public string UserName; public string LicenseKey; } 4. In the Web service class declare a public instance of the header class.

public class HeaderService : System.Web.Services.WebService { ... public EchoHeader UserHeader; 5. Apply the [SoapHeader] attribute to the Hello() method.

[WebMethod] [SoapHeader("UserHeader")] public string Hello() { 6. Modify the return statement in the Hello() to return hello followed by the user name,

which is obtained from the UserHeader object.

[WebMethod] [SoapHeader("UserHeader")] public string Hello() { return "Hello, " + UserHeader.UserName; } 7. Compile your program to make sure there are no compile errors at this point. You

may run the program from within Visual Studio to bring up the test page (but you won’t succeed in invoking the Hello() method, because of the requirement for the client to send header information). If you would like to test your Hello() method before going on to implement the Reverse() method, proceed to Part 2. Otherwise, continue with the server program until finished.

8. Create a helper method ReverseString() that will reverse a string, making use of the StringBuilder class. Add a using statement for the namespace System.Text.

private string ReverseString(string str) { int len = str.Length; StringBuilder rev = new StringBuilder(str); for (int i = 0; i < len; i++) rev[i] = str[len - 1 - i]; return rev.ToString(); }

Page 90: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 246 All Rights Reserved

9. Add a Web Method Reverse() which takes an input string parameter and returns a string. The license key is checked against “0”. If it agrees, the string is reversed and returned; otherwise an error message is returned.

10. Build your Web service, and make it an application in IIS. Proceed with Part 2.

Part 2. Implement the Client Program 1. Build and run the starter program, which provides a user interface for exercising the

HeaderService Web service. The starter code provides no code yet, but for convenience the one legal license key value of “0” is given as starting data.

2. Create the proxy via the wsdl.exe tool. Start a Visual Studio 2005 command prompt, and enter the following command. For convenience, we provide a batch file wsdlbuild.bat.

wsdl /l:C# http://localhost/WsNetCs/Labs/Lab7A/HeaderService/ HeaderService.asmx?WSDL 3. Examine the code for the proxy file HeaderService.cs, which should be added to

your project. Notice the classes HeaderService and EchoHeader.

4. Add code to declare variables proxy and header.

HeaderService proxy; EchoHeader header; 5. Add a handler for the Load event to instantiate proxy and header.

6. Create a helper method to initialize the header and the EchoHeaderValue property of the proxy.

private void InitHeader() { header.UserName = txtUser.Text; header.LicenseKey = txtLicense.Text; proxy.EchoHeaderValue = header; } 7. Add a handler for the Hello button. Add code to this handler to initialize the header

and then call the Hello() method of the proxy. Display the returned value in txtResult.

8. Add a project reference to assembly System.Web.Services.

9. Build and run. You should be able to exercise the Hello() method at this point. If you are testing incrementally and have not yet completed the server program, delete the generated HelloService.cs from the client project in preparation for adding it again after you have implemented the Reverse() method on the Web server.

Page 91: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 247 All Rights Reserved

10. Add a handler for the Reverse button. Add code to this handler to initialize the header and then call the Reverse() method of the proxy. Display the returned value in txtResult.

11. Build and test. Be sure to check both legal and illegal license keys.

Page 92: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 248 All Rights Reserved

Lab 7B

Using SOAP 1.1 and SOAP 1.2

Introduction In this lab you will experiment with using either SOAP 1.1 or SOAP 1.2 in calling a Web service. You will implement a client program that can make a Web service request using either protocol. You will also experiment with the Web service by removing support for one or the other of the protocols.

Suggested Time: 20 minutes Root Directory: OIC\WsNetCs Directories: Labs\Lab7B (do your work here) Chap07\DocMath (server)

Chap07\SoapClient\Step0 (starter code backup) Chap07\SoapClient\Step1 (solution)

Instructions 1. Build and run the starter program, which provides a user interface for exercising the

DocMath Web service. The starter code provides no code yet, except for initializing the radio buttons for SOAP Version to 1.1 checked.

2. Add a Web Reference to the DocMath Web service.

3. Add these using statements to Form1.cs:

using SoapClient.localhost; using System.Web.Services.Protocols;

Page 93: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 249 All Rights Reserved

4. Add handlers for the Add and Subtract buttons.

5. Add code to each handler that will instantiate a proxy object and set the SoapVersion property on the proxy object to the proper value, depending on which radio button is checked.

DocMath ws = new DocMath(); if (rad11.Checked) ws.SoapVersion = SoapProtocolVersion.Soap11; else if (rad12.Checked) ws.SoapVersion = SoapProtocolVersion.Soap12; 6. Provide code in the Add handler that will invoke the Add() method of the proxy

object to add the two numbers in the textboxes and display the result in the Answer textbox.

int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int answer = ws.Add(x, y); txtAnswer.Text = answer.ToString(); 7. Provide similar code in the Subtract handler to perform subtraction through the proxy

object.

8. Build and test. Since by default by SOAP 1.1 and SOAP 1.2 are enabled, both protocols should work.

9. Examine the Web.config file in the DocMath Web service.

<?xml version="1.0"?> <configuration> <system.web> <webServices> <protocols> <!-- <remove name ="HttpSoap12"/> --> </protocols> </webServices> </system.web> </configuration> 10. We’ve commented out the line that removes the SOAP 1.2 protocol. Uncomment this

line and save the modified Web.config file. Now run the client program again. This time the SOAP 1.1 option should work but not the SOAP 1.2.

11. Modify the Web.config file to remove instead the protocol HttpSoap. Now SOAP 1.1 will fail but SOAP 1.2 will work.

Page 94: Web Services Using C# and ASP - ITCourseware · Web Services Using C# and ASP.NET Rev. 3.0 ... Service Oriented Architecture (SOA) ... WCF Services

WsNetCs Chapter 7

Rev. 3.0 Copyright © 2009 Object Innovations Enterprises, LLC 250 All Rights Reserved