82
Object Innovations Course CS31 Student Guide Revision 2.0 .NET Distributed Applications Using C#

CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Embed Size (px)

Citation preview

Page 1: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Object Innovations Course CS31

Student Guide Revision 2.0

.NET Distributed Applications Using C#

Page 2: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC ii All Rights Reserved

.NET Distributed Applications Using C# Rev. 2.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. Copyright ©2006 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

Page 3: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 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 Data Access with Web Services Chapter 9 WSE 3.0 and Web Services Security Chapter 10 .NET Remoting Appendix A Learning Resources Appendix B Configuring IIS for ASP.NET 2.0

Page 4: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• Install the course software by running the self-extractor Install_WsNetCs_20.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: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 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 Microsoft MapPoint – S2C and S2B ................................................................................ 18 Service to Business Web Services .................................................................................... 19 Dollar Rent a Car – B2B................................................................................................... 20 Service Oriented Architecture (SOA)............................................................................... 21 Services Are Independent ................................................................................................. 22 ASP.NET Web Services ................................................................................................... 23 Alternative Technologies.................................................................................................. 24 Web Service Enhancements 3.0........................................................................................ 25 Windows Communication Framework ............................................................................. 26 Summary ........................................................................................................................... 27

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

Page 6: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC vi All Rights Reserved

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

Chapter 3: Developing ASP.NET Web Services .............................................................. 69 Developing Web Services in Visual Studio 2005............................................................. 71 Visual Studio Web Service Demo .................................................................................... 72 Code for a Simple Web Service........................................................................................ 74 Hello World Web Service................................................................................................. 75 Concatenate Web Service ................................................................................................. 76 WebService Directive ....................................................................................................... 81 Service.cs .......................................................................................................................... 82 System.Web.Services Namespace .................................................................................... 83 WebService Attribute ....................................................................................................... 84 WebMethod Attribute ....................................................................................................... 85 BufferResponse................................................................................................................. 86 MessageName................................................................................................................... 87 Turning Off Conformance Checking ................................................................................ 91 WS-I Basic Profile ............................................................................................................ 92 ASP.NET Configuration ................................................................................................... 93 Multi-level Configuration ................................................................................................. 94 Configuration Hierarchy ................................................................................................... 95 Lab 3A .............................................................................................................................. 96 WebService Class ............................................................................................................. 97 Sample Program – Utility ................................................................................................. 98 Lab 3B............................................................................................................................. 101 Lab 3C............................................................................................................................. 102 Summary ......................................................................................................................... 103

Chapter 4: Web Service Clients ...................................................................................... 117 Protocols ......................................................................................................................... 119 Accessing a Web Service................................................................................................ 120 Creating a Proxy ............................................................................................................. 121

Page 7: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC vii All Rights Reserved

Creating a Proxy using wsdl.exe..................................................................................... 122 Exploring the Generated Proxy Code ............................................................................. 123 Console Client Test Program.......................................................................................... 126 Creating a Proxy via Visual Studio................................................................................. 127 Web Client Demo ........................................................................................................... 128 Lab 4A ............................................................................................................................ 131 Lab 4B............................................................................................................................. 132 Lab 4C (Optional) ........................................................................................................... 133 Summary ......................................................................................................................... 134

Chapter 5: ASP.NET Web Services Programming Model ........................................... 143 Asynchronous Programming in Web Services ............................................................... 145 Example – Asynchronous Call........................................................................................ 146 Begin and End Asynchronous Methods.......................................................................... 148 Using a Callback Delegate.............................................................................................. 150 Example – Asynch Concatenate ..................................................................................... 152 Asynchronous Events in .NET 2.0.................................................................................. 153 Lab 5A ............................................................................................................................ 154 State Management in ASP.NET ..................................................................................... 155 Application and Session Objects .................................................................................... 156 Session Management ...................................................................................................... 157 Application Management................................................................................................ 158 Example – StateService .................................................................................................. 159 ASP.NET Web Services Transactions............................................................................ 161 Caching: An Overview ................................................................................................... 163 Data to be Cached – Time Frame ................................................................................... 164 Output Caching ............................................................................................................... 165 Output Caching Example................................................................................................ 166 Debugging....................................................................................................................... 167 Debugging a Web Service .............................................................................................. 168 Enable Debugging in Web.config................................................................................... 169 Deploying a Web Service ............................................................................................... 171 Lab 5B............................................................................................................................. 174 Summary ......................................................................................................................... 175

Chapter 6 XML Serialization ........................................................................................ 183 Serialization in .NET ...................................................................................................... 185 Serialization Demonstration ........................................................................................... 186 CLR Serialization ........................................................................................................... 187 Circular List and XML Serialization .............................................................................. 190 XML Serialization Demo................................................................................................ 191 XML Serialization Infrastructure.................................................................................... 196 What Will Not Be Serialized .......................................................................................... 197 XML Schema .................................................................................................................. 198 XSD Tool ........................................................................................................................ 199 A Sample Schema ........................................................................................................... 200

Page 8: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC viii All Rights Reserved

The XML Designer ......................................................................................................... 201 A More Complex Schema............................................................................................... 202 A Car Dealership ............................................................................................................ 203 Deserializing According to a Schema............................................................................. 204 Sample Program.............................................................................................................. 205 Type Infidelity ................................................................................................................ 206 Example – Serializing an Array...................................................................................... 207 Example – Serializing an ArrayList................................................................................ 210 Customizing XML Serialization..................................................................................... 212 Lab 6A ............................................................................................................................ 213 XML Serialization and Web Services ............................................................................ 214 ArrayList Web Service Example .................................................................................... 215 Lab 6B............................................................................................................................. 216 Summary ......................................................................................................................... 217

Chapter 7: More about SOAP ......................................................................................... 223 The SOAP Messaging Model ......................................................................................... 225 SOAP Namespaces ......................................................................................................... 226 The SOAP Envelope ....................................................................................................... 227 The Message Header....................................................................................................... 228 Using SOAP Headers in .NET........................................................................................ 229 Using SOAP Headers on the Client ................................................................................ 231 SOAP Header Example................................................................................................... 232 Call Body ........................................................................................................................ 234 Response Body................................................................................................................ 235 Lab 7A ............................................................................................................................ 236 Returning Errors ............................................................................................................. 237 Example – SOAP Fault ................................................................................................... 238 Document Style Web Services........................................................................................ 239 Document vs. RPC Style................................................................................................. 240 Wrapped vs. Bare Style................................................................................................... 241 Literal vs. Encoded Use .................................................................................................. 242 Example – Bare Document Style.................................................................................... 243 More Document Style Examples .................................................................................... 245 RPC Style Examples ....................................................................................................... 246 SOAP 1.2 ........................................................................................................................ 247 Specifying the Transport Protocols................................................................................. 248 Making a Request Using SOAP 1.2................................................................................ 249 Lab 7B............................................................................................................................. 250 Summary ......................................................................................................................... 251

Chapter 8: Data Access with Web Services.................................................................... 259 Multiple-Project Solutions.............................................................................................. 261 Demo: A Two-Project Solution ...................................................................................... 262 A Windows Application Client Project .......................................................................... 264 Adding a Web Reference ................................................................................................ 266

Page 9: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC ix All Rights Reserved

Multiple Projects in Solution Explorer ........................................................................... 267 Implementing a Client Proxy.......................................................................................... 268 Lab 8A ............................................................................................................................ 269 Multiple-Tier Data Access.............................................................................................. 270 Sample Database............................................................................................................. 271 Data Access Example ..................................................................................................... 272 Data Access Demo.......................................................................................................... 274 A Data Access Web Service ........................................................................................... 281 An Enhanced Web Service ............................................................................................. 285 Client for Enhanced Web Service................................................................................... 288 Objects in a ListBox ....................................................................................................... 289 Web Services Pass Data.................................................................................................. 290 LocalCourse .................................................................................................................... 291 Client Code ..................................................................................................................... 292 Type Information in Web Services ................................................................................. 294 TypedDataDemo Example.............................................................................................. 295 Type Information as XML Schema ................................................................................ 296 Typed DataSets in Web Services.................................................................................... 297 Adding a Typed DataSet................................................................................................. 298 Returning a Typed DataTable......................................................................................... 300 Binding to a Web Service ............................................................................................... 301 Troubleshooting Tip ....................................................................................................... 305 Lab 8B............................................................................................................................. 306 Summary ......................................................................................................................... 307

Chapter 9: WSE 3.0 and Web Services Security ........................................................... 315 Web Services Enhancements .......................................................................................... 317 Windows Communication Foundation ........................................................................... 318 When to Use WSE 3.0 .................................................................................................... 319 WSE Architecture ........................................................................................................... 320 A WSE-Enabled Web Service ........................................................................................ 321 WSE Settings 3.0 Tool.................................................................................................... 322 WSE Message Tracing.................................................................................................... 323 Configuration File........................................................................................................... 324 Testing the Web Service ................................................................................................. 325 InputTrace.webinfo......................................................................................................... 327 OutputTrace.webinfo ...................................................................................................... 329 WSE Generated Headers................................................................................................. 330 SOAP 1.2 ........................................................................................................................ 331 Math Web Service Code ................................................................................................. 332 Math Client Code............................................................................................................ 333 A WSE-Enabled Client ................................................................................................... 334 WebServicesClientProtocol ............................................................................................ 337 WSE without Visual Studio ............................................................................................ 338 Lab 9A ............................................................................................................................ 339 Web Services Security .................................................................................................... 340

Page 10: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

Rev. 2.0 Copyright ©2006 Object Innovations Enterprises, LLC x All Rights Reserved

Server Authentication ..................................................................................................... 341 Client Code Using the Policy.......................................................................................... 342 Policy File ....................................................................................................................... 343 Test X.509 Certificates ................................................................................................... 344 Anonymous Security Demo............................................................................................ 346 Policy Configuration File................................................................................................ 351 Service.cs ........................................................................................................................ 352 Enabling Policy in the Client .......................................................................................... 353 Application Configuration File ....................................................................................... 355 Anonymous Client Code................................................................................................. 356 User Name Authentication.............................................................................................. 357 User Name Authentication – Server ............................................................................... 358 User Name Authentication – Client................................................................................ 359 Lab 9B............................................................................................................................. 360 Summary ......................................................................................................................... 361

Chapter 10 .NET Remoting ........................................................................................... 369 Distributed Programming in .NET.................................................................................. 371 .NET Remoting Architecture .......................................................................................... 372 Remote Objects and Mobile Objects .............................................................................. 374 Object Activation and Lifetime ...................................................................................... 375 Singleton and SingleCall ................................................................................................ 376 .NET Remoting Example................................................................................................ 377 .NET Remoting Example: Defs ..................................................................................... 378 .NET Remoting Example: Server .................................................................................. 379 .NET Remoting Example: Client ................................................................................... 381 Lab 10 ............................................................................................................................. 383 Summary ......................................................................................................................... 384

Appendix A: Learning Resources.................................................................................... 387

Appendix B: Configuring IIS for ASP.NET 2.0............................................................. 391 ASP.NET Versions Side-by-Side ................................................................................... 392 Configuring for ASP.NET 2.0 ........................................................................................ 393 Installing ASP.NET ........................................................................................................ 396

Page 11: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

What Are Web Services?

Page 12: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 13: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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.

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

• Technically speaking, a Web service does not execute, but the application that produces or consumes the Web service does.

Page 14: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 15: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 5 All Rights Reserved

Distributed Object Computing

• Building scalable solutions require applying the appropriate level of compute 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 16: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 17: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 18: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 19: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 20: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 21: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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.0 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.0.

Page 22: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 23: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 24: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 25: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 26: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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 realistic business models of Web services with real life case studies.

Page 27: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 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.

• We will see some real-life examples of S2C and S2B.

Page 28: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 18 All Rights Reserved

Microsoft MapPoint – S2C and S2B

• Home page of Microsoft MapPoint Web service:

http://www.microsoft.com/mappoint/webservice/default.mspx

− The Microsoft MapPoint Web Service allows developers to integrate location-based services, such as maps and driving directions into their applications and business processes.

− It also provides mapping-related content, such as business listings and points-of-interest that can be used within applications.

Page 29: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 19 All Rights Reserved

Service to Business Web Services

• S2B Web services enable better communication to business partners to share data regardless of the platform and operating systems.

• Case Study: Dollar Rent a Car

• Let us explore the Dollar Rent a Car – B2B Electronic Commerce scenario. For more info about this take a look at the provided link:

http://www.microsoft.com/resources/casestudies/ShowFile.asp?FileResourceID=248

− Dollar Rent a Car is one of the world’s largest car rental agencies, with more than 400 locations in 26 countries.

− To open up new business opportunities, Dollar wanted to provide partners with direct access into its reservation system a VMS-based application known as Quick Keys.

− Dollar's Advanced Technology Group identified four possible technologies for connecting with other systems CORBA and the Internet Interoperability ORB Protocol (IIOP), Java RMI, DCOM, and socket programming—but uncovered significant issues with each option.

− In a UNIX-to-UNIX environment, CORBA and IIOP are commonly used to connect two systems. When the team priced a CORBA ORB, they found that the cost would be in the neighborhood of six figures—which was cost prohibitive.

Page 30: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 20 All Rights Reserved

Dollar Rent a Car – B2B

− In addition, taking this approach would have required opening ports in Dollar's firewall for outside access, which did not please the company's IT security team.

− Java was not in use at Dollar, and would have required them to add another complex technology to their existing environments.

− DCOM was created a several years ago, and is optimized to work over high-speed local area networks rather than a non-deterministic channel such as the Internet.

• Unhappy with all commercially available options, Dollar did have one other choice: XML Web services.

− By integrating directly with business partners using the Microsoft platform and XML Web services, Dollar cost-effectively opened up another sales channel that has provided millions of additional rate requests and thousands of new reservations per year, equating to millions of dollars in additional revenue.

• Such case studies point to how Web services reduce application development cost, solve interoperability issues and provide new sources of revenue.

− For more case studies, visit Microsoft’s case studies Web site:

http://www.microsoft.com/resources/casestudies/default.asp

Page 31: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 21 All Rights Reserved

Service Oriented Architecture (SOA)

• Objects do not naturally 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 32: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 22 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. Compensation is used to reverse changes.

− 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 33: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 23 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 2005 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 34: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 24 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 35: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 25 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

Page 36: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 26 All Rights Reserved

Windows Communication Framework

• WCF, formerly “Indigo,” will unify the programming model for the various distributed technologies.

− The programmer will not need to be familiar with all the WS* specifications.

− WSE 3.0 is an approximation of WCF

• WSE is for early adopters who need to use the leading edge SOA technology to enhance ASMX, but migrating code will be an issue.

− First mover advantage is more important than code portability.

− Abstract away or avoid using ASMX extensibility features such as the HTTP Context object.

• .NET Remoting

− Extensibility features such as custom sinks and channels will require major code migration work.

• Enterprise Services

− Avoid passing object references inside of the Enterprise Services.

− Do not use the COM+ API; use System.EnterpriseServices.

− Do not use the MSMQ API; use System.Messaging.

Page 37: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 27 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 the best current Microsoft technology match for implementation.

− Other Microsoft Web service technologies are WSE 3.0 and WCF.

Page 38: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 1

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 28 All Rights Reserved

Page 39: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 117 All Rights Reserved

Chapter 4

Web Service Clients

Page 40: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 118 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.

• Write a client for a real-life Web service, such as the Google search API.

Page 41: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 119 All Rights Reserved

Protocols

• The following three types of protocols can be used 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 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 is written to a separate line sent with the HTTP header, and the data is not directly visible to the outside world.

− But the supported data types by the 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 does not support all the data types, only ones with a simple UI. Array input is not supported by the test form.)

− You cannot make use of the 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 42: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 120 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.

− Add the proxy class namespace to your client application, create an instance of the proxy class and invoke the Web service methods using that proxy.

Page 43: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 121 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 44: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 122 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 go through all the flags of the wsdl.exe utility by simply typing wsdl in the command prompt.

Page 45: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 123 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 46: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 124 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 47: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 125 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 48: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 126 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: spider-man

Page 49: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 127 All Rights Reserved

Creating a Proxy via Visual Studio

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

− 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.

1. Create a new Visual Studio ASP.NET Web Site WebClient.

2. Create a user interface as shown:

Page 50: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 128 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 over References 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 51: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 129 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 52: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 130 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.

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

Page 53: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 131 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 54: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 132 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 55: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 133 All Rights Reserved

Lab 4C (Optional)

Google Web Service API

In this lab you will construct a client which consumes a real-life Web service, the Google Web service API. You will need a connection to the Internet.

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

Page 56: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 134 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 57: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 135 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 58: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 136 All Rights Reserved

Copy the URL http://localhost/WsNetCs/Chap03/SortService/SortService.asmx 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 59: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 137 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 2005 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 60: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 138 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 2005 by using the Add Web Reference technique. Modify your code to use this proxy instead.

Page 61: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 139 All Rights Reserved

Lab 4C

Google Web Service API Programming (Optional)

Introduction In this lab you will construct a client which consumes a real-life Web service, the Google Web service API. For this lab you will need a connection to the Internet. With the Google Web Service, software developers can query more than 3 billion Web documents directly from their own computer programs. Google uses the SOAP and WSDL standards so a developer can program in his or her favorite environment —such as Java, Perl, or .NET. Google provides each developer who registers to use the Google Web APIs service a limit of 1,000 queries per day. For more information about the Google Web Service visit the following URL: http://www.google.com/apis/ Suggested Time: 60 minutes Root Directory: OIC\WsNetCs Directories: Labs\Lab4C (do your work here) Chap04\MyGoogle (answer) To start writing programs using Google Web APIs the steps to be followed are: Download the developer's kit

The Google Web APIs developer's kit offers documentation and example code (.NET, Perl, and Java examples and a WSDL file) for using the Google Web APIs service. http://www.google.com/apis/download.html (This is for further reference).

Create a Google Account

To access the Google Web APIs service, you must create a Google Account and obtain a license key. Your Google account and license key allow you to 1,000 automated queries per day. Your license key will be emailed to you.

Write your program using your license key

Your program must include your license key with each query you submit to the Google Web APIs service.

Page 62: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 140 All Rights Reserved

Create a Windows Forms Google Application 1. In Visual Studio select the menu File | New | Project.….

2. In the New Project dialog box choose “Visual C#” as the Project Type and “Windows Application” as the Template.

3. Navigate to Labs\Lab4C as the Location of your project and enter MyGoogle as the Name of your project. Click OK.

Using the Form Designer

1. Bring up the Toolbox from the View menu, if not already showing.

2. Drag the controls and design the GUI as shown in the screen capture.

3. Add a PasswordChar to the textbox for the LicenseKey.

4. Add a Web reference using the WSDL found at the following URL on the Google site: http://api.google.com/GoogleSearch.wsdl. You should then see information about the Google Web service displayed, as shown in the screen capture on the following page. Click Add Reference.

Page 63: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 141 All Rights Reserved

5. If you like, you can examine the WSDL file in Internet Explorer.

Page 64: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 4

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 142 All Rights Reserved

6. When working with a proxy, you can examine the file Reference.cs to determine the namespace and the class of the proxy. Note that now this file is located in the folder Web References\com.google.api.

7. Add the following using statement to the file Form1.cs. You could fill it in via auto-complete, beginning with using MyGoogle. The part com.google.api is what is shown under Web References. Before, when using our local computer, it was always localhost.

using MyGoogle.com.google.api; 8. Add some initialization code to the form’s Load event to simplify your testing (so

you won’t have to keep typing the information in).

private void Form1_Load(object sender, System.EventArgs e) { txtLicKey.Text = "YOUR KEY HERE"; txtQuery.Text = @"YOUR QUERY STRING HERE"; txtStart.Text = "0"; } 9. Add a handler for the Search button.

10. In the handler instantiate a proxy object and call the doGoogleSearch() method. This call has quite a few parameters. You may study the documentation provided when you download the developer's kit, which also includes a C# demo program. The following code fragment illustrates a suitable call:

GoogleSearchResult r = ws.doGoogleSearch( txtLicKey.Text, // license key txtQuery.Text, // query string start, // start 10, // maxResult (<= 10) false, // filter "", // restricts false, // safeSearch "", // language restricts "", // input encoding (deprecated) "" // output encoding (deprecatd) ); 11. Finish implementing the handler for Search to accomplish the following:

a. Show the estimated number of results.

b. Display the URLs of the results in the listbox.

c. Increment the starting index by the number of results returned on this call (normally you will get 10 results per call if you ask for them).

12. Build and test.

Page 65: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 369 All Rights Reserved

Chapter 10

.NET Remoting

Page 66: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 370 All Rights Reserved

.NET Remoting

Objectives

After completing this unit you will be able to:

• Compare the two distributed programming techniques supported by the .NET Framework: Web services and .NET remoting.

• Explain the differences between marshal by value and marshal by reference and write programs using both techniques.

• Implement a distributed application using .NET remoting.

Page 67: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 371 All Rights Reserved

Distributed Programming in .NET

• Microsoft .NET provides two technologies to support distributed programming: Web services and .NET remoting.

• Web services use XML and HTTP based protocols to provide an industry standard to allow diverse systems to interconnect.

− Hence with Web services you can interoperate with non-.NET platforms.

− Web services are based on SOAP, an acronym originally meaning Simple Object Access Protocol.

− Web services have a simple architecture but are also somewhat limited, for example always being stateless.

• .NET remoting is the replacement for DCOM, providing a very powerful distributed technology.

− It allows clients to create objects in another process or on another machine and use them like local objects.

− The remote object may either retain state, or be stateless to support scalability.

− Great flexibility is provided, such as a choice of SOAP-based or efficient binary/TCP communications channel.

− But .NET remoting is not for heterogeneous environments; it requires the .NET platform on both sides.

Page 68: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 372 All Rights Reserved

.NET Remoting Architecture

• With .NET remoting a client calls the remote object through a proxy and various layers implemented by the .NET Framework.

− These layers can either be extended or completely replaced, and other layers can be chained in, resulting in a very flexible architecture.

ClientApp

Proxy Formatter Channel

Dispatcher

ServerObject

ChannelFormatter

Page 69: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 373 All Rights Reserved

.NET Remoting Architecture (Cont’d)

• The client application calls a proxy, which is a stand-in, in the client’s own app domain, for the remote object.

• Every method call into the proxy is converted into a message, which passes through various layers.

− The formatter converts the message into a particular format, such as SOAP or a binary format. Objects are serialized into a linear stream of bytes.

− The channel uses a protocol such as TCP or HTTP to cross a process or machine boundary.

− On the server side, a channel receives the message and a formatter deserializes the objects in the message.

− A dispatcher calls the target object and passes back responses through the various layers.

Page 70: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 374 All Rights Reserved

Remote Objects and Mobile Objects

• The target object in another process or machine is a remote object.

− The remote object can execute methods called by remote clients, receiving parameters and passing back return values.

− The remote object stays at the server, and only references are passed around.

− In .NET, remote objects are represented by classes which inherit from MarshalByRefObject. They are sometimes called marshal-by-reference or MBR objects.

• Mobile objects are serialized into a byte stream in a definite format, such as XML or a binary format, and deserialized at the other end.

− Client and server each hold a copy of the same object. The value of the object is passed.

− Calls on a mobile object are always carried out in a local context on the copy of the object and never travel to the remote process or machine from which the object originated.

− In .NET, mobile objects are represented by classes which either have the [Serializable] attribute or implement the ISerializable interface. They are sometimes called marshal-by-value or MBV objects.

Page 71: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 375 All Rights Reserved

Object Activation and Lifetime

• A local object is activated (or created) by new.

− It remains active as long as there is some reference to it.

− When there are no more references, it becomes garbage, and its memory is eventually reclaimed by the garbage collectors.

• Activation and lifetime is completely different for remote objects. There are two kinds of activation:

− Server activation

− Client activation

• Server-activated objects are created “on demand” by the server when they are needed, when the client invokes the first method on the proxy.

− This saves a round trip to the server for the purpose of creating the object, but it means that only a default constructor (having no parameters) is available.

• Client-activated objects are created on the server in response to the client calling new or Activator.GetObject.

Page 72: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 376 All Rights Reserved

Singleton and SingleCall

• There are two kinds of server-activated objects, Singleton and SingleCall.

− The WellKnownObjectMode enumeration is used in RemotingConfiguration.RegisterWellKnownServiceType to specify Singleton or SingleCall.

• A Singleton type of object can have only one instance at any given time.

− The instance will be created on the first method call, and subsequent method calls will be to the same instance.

− A Singleton type of object has a default lifetime, so if no requests are received during this period, the object will be destroyed, and later requests will be to a different single instance.

• A SingleCall type of object has a new instance created for each request.

− This object is destroyed after the request is completed.

− SingleCall objects cannot hold state information and thus can be highly scalable.

Page 73: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 377 All Rights Reserved

.NET Remoting Example

• Our example program illustrates a server-activated remote object.

− Variations of the program illustrate both Singleton and SingleCall, and also passing of both a mobile and a remote object.

− The mainstream version is a Singleton with a mobile object passed as a parameter (marshal-by-value).

− See RemoteAccount.

• A typical .NET Remoting application has three components:

− Common definitions of interfaces and classes that are used by both the server and the client.

− The server code.

− The client code.

• In the example, there are separate solutions Server and Client. The server solution contains a Defs project as well as a Server project.

• There is also a solution Monolithic, which illustrates the same functionality in a purely local version.

Page 74: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 378 All Rights Reserved

.NET Remoting Example: Defs

using System; namespace Defs { public interface IAccountManager { Account GetAccount(int id); } [Serializable] public class Account //public class Account : MarshalByRefObject { public int Id; public decimal Balance; public Account() { Console.WriteLine( "Account object created"); } public Account(int vId, decimal vBalance) { Id = vId; Balance = vBalance; Console.WriteLine("Account object created, Id = {0}, Balance = {1}", vId, vBalance); } public void Deposit(decimal amount) { Balance += amount; } public void Withdraw(decimal amount) { Balance -= amount; } } }

Page 75: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 379 All Rights Reserved

.NET Remoting Example: Server

using System; using System.Collections; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using Defs; namespace Server { public class Bank : MarshalByRefObject, IAccountManager { private ArrayList m_list; public Bank() { m_list = new ArrayList(); m_list.Add(new Account(1, 100)); m_list.Add(new Account(2, 200)); m_list.Add(new Account(3, 300)); Console.WriteLine( "Bank object created"); } public Account GetAccount(int id) { foreach (Account acc in m_list) { if (acc.Id == id) return acc; } return null; } } ...

Page 76: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 380 All Rights Reserved

Server (Cont’d)

public class Server { static void Main(string[] args) { TcpServerChannel chan = new TcpServerChannel(123); ChannelServices.RegisterChannel(chan); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Bank), "Bank.rem", WellKnownObjectMode.Singleton); //WellKnownObjectMode.SingleCall); Console.WriteLine("Server started"); System.Console.WriteLine( "Hit <enter> to exit..."); System.Console.ReadLine(); } } }

• The remote object is Bank, which must inherit from MarshalByRefObject.

• The server startup code does the following:

− Create a channel configured to listen on a certain port.

− Register the channel with the remoting system.

− Register the service type, specifying the type of object, a URL (bank.rem) that will be used by the client, and the type of server-activated object (Singleton or SingleCall).

− A startup message is displayed, and the server waits for console input to close.

Page 77: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 381 All Rights Reserved

.NET Remoting Example: Client

using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using Defs; namespace Client { public class RemoteClient { static void Main(string[] args) { TcpClientChannel chan = new TcpClientChannel(); ChannelServices.RegisterChannel(chan); IAccountManager b = (IAccountManager)Activator.GetObject( typeof(IAccountManager), @"tcp://localhost:123/Bank.rem"); if (b == null) { System.Console.WriteLine( "Could not locate server"); return; } Continue(); Account acc = b.GetAccount(1); ShowBalance(acc); acc.Deposit(25); ShowBalance(acc); Continue(); acc = b.GetAccount(1); ShowBalance(acc); ...

Page 78: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 382 All Rights Reserved

Client (Cont’d)

System.Console.WriteLine( "Hit <enter> to exit..."); System.Console.ReadLine(); } static void Continue() { Console.WriteLine( "Press <enter> to continue"); System.Console.ReadLine(); } static void ShowBalance(Account acc) { if (acc == null) Console.WriteLine("Account is null"); else Console.WriteLine( "Balance = {0:C}", acc.Balance); } } }

− A channel is created and registered.

− The call to Activator.GetObject() creates a local proxy object that talks to the remote server.

− The helper method Continue() can be used to pause the run of the client program so that output from the client console and the server console can be compared.

Page 79: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 383 All Rights Reserved

Lab 10

Experimenting with .NET Remoting

In this lab you will build and run the .NET Remoting example we have just examined, beginning with a purely local version of the program. By commenting and uncommenting code you can observe different behaviors for Singleton vs. SingleCall and mobile object vs. remote object.

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

Suggested time: 30 minutes

Page 80: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 384 All Rights Reserved

Summary

• The.NET Framework supports two distributed programming techniques: Web services and .NET remoting.

• .NET Remoting is a flexible architecture that can use different channels and formatters.

• Mobile objects use marshal-by-value, and remote objects use marshal-by-reference.

• Remote objects can be client-activated or server-activated, and the latter can be Singleton or SingleCall.

Page 81: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 385 All Rights Reserved

Lab 10

Experimenting with .NET Remoting

Introduction In this lab you will build and run the .NET Remoting example we have just examined, beginning with a purely local version of the program. By commenting and uncommenting code you can observe different behaviors for mobile object vs. remote object and Singleton vs. SingleCall. Suggested Time: 30 minutes Root Directory: OIC\WsNetCs Directories: Labs\Lab10\RemoteAccount (do your work here) Chap10\RemoteAccount (backup copy) Instructions Before beginning with the step-by-step instructions, spend a few minutes examining the general structure of the solutions. The Monolithic solution, as its name suggests, is completely self-contained. There is a single project, and the definitions file Defs.cs is part of the project. The Server solution contains two projects, Defs and Server. Whenever you change the Defs.cs file, you should rebuild the server. The Client solution contains just one project, Client. It references the DLL Defs.dll. The Copy Local property for this reference is set to false. The output files from both Server and Client are written to the top-level RemoteAccount directory, making it easy for the .exe files to find Defs.dll. The solutions have been structured in this way to make it easy to experiment with making various changes to Defs.cs and be sure that you are working with up-to-date files. As a check, you will be instructed to change the static member Version of the Account class when you modify the class. Both server and client show this version number on start up. (The code listings in the lecture omit this Version information, for simplicity.) 1. Examine the code for the Monolithic solution. Before running the program, predict

what the output will be. Run the program and make sure you understand the output. Exit the app.

2. Examine the code for the Server solution. Build and run. Leave the console window for this running app open.

3. Examine the code for the Client solution. Before running the program, predict what the output will be, both on the client console and on the server console. Build and run, and make sure you understand the outputs. Arrange the console windows of the server and client side-by-side. In particular, why is the balance of the last account object

Page 82: CS31 Contents 20 - itcourseware.com · .NET Distributed Applications Using C# Rev. 2.0 Student Guide ... Chapter 5 ASP.NET Web Services Programming Model Chapter 6 XML Serialization

WsNetCs Chapter 10

Rev. 2.0 Copyright © 2006 Object Innovations Enterprises, LLC 386 All Rights Reserved

different in this scenario ($100.00) than it was in the monolithic scenario ($125.00)? Close out both the client and server apps.

4. In the Server solution, comment out the [Serializable] attribute for the Account class. Set the version number for Account to 2. Build and run. Leave the console window for this running app open.

5. Build and run the client. Make sure that the client is also working with version 2 of Account. What happens?

6. There is an exception, because we are trying to pass an Account object by value, and it is not serializable. In the Server solution create a third version of the Account object by making the Account class inherit from MarshalByRefObject, making Account a remote object in place of a mobile object. Set the version number to 3.

7. Build and run the client. Make sure that the client is also working with version 3 of Account. What happens?

8. The program works again, but there is a different result for the balance of the last account object. We are not working with a copy of an account, but a remote object, whose balance has been changed to $125.00, which is now shown as the balance (like in the monolithic case!).

9. Back in the Server solution, change the server startup code to register the server as a SingleCall type. Build and run the server, leaving the console window open.

10. Build and run the client. Explain the output.

11. If you have extra time, perform additional experiments, such as running the client from a different computer over the network, replacing the channel by an HTTP channel, and so forth.