My Profile
Active Members
TodayLast 7 Days
more...
Awards & Gifts
Online Exams
Fresher Jobs
Our fresher job section is exclusively for fresh graduates! Find jobs for freshers in major Indian
cities including Bangalore, Chennai, Hyderabad, Pune or Kochi
Resources
Find educational articles, blogs, discussion threads and other resources.
Colleges
Find details about any college in India or search for courses.
Paid Surveys
|
.NET Web Services Tutorial
Posted Date: 21 May 2008 Resource Type: Articles/Knowledge Sharing Category: Computer & Technology
|
Posted By: Saradhi Gollangi Member Level: Bronze Rating: Points: 1
|
|
|
|
Abstract This is not a Visual Studio walkthrough of Web Services. For a Visual Studio perspective, see the Visual Studio documentation. This is a look at Web Services as it pertains to the .NET framework at the core level. This tutorial provides an overview of how Web Services work and walks you through creating, publishing, testing and calling Web Services using the .NET framework. This tutorial also addresses issues of data types, wire transmissions and using ASP.NET services.
At the end of this module, you will be able to: • Describe the programming model and application architecture of Web Services • Build a Web Service • Test a Web Service • Publish a Web Service • Call a Web Service • Determine when to use POST, GET, or SOAP for different data types
Contents 1. Introduction 2. Common Concepts 3. Creating the “Hello World” Web Service 4. Testing the “Hello World” Web Service 5. Publishing the “Hello World” Web Service 6. Calling the “Hello World” Web Service 7. Anatomy of a Web Service Request 8. Data Types Supported 9. ASP.NET Services 10. Summary 11. Food for Thought 12. APPENDIX A: Web Service Scenarios 13. APPENDIX B: WebServiceUtil 14. APPENDIX C: Additional Resources Introduction This tutorial assumes you already have the .NET Framework SDK or Visual Studio.NET Prerequisites • XML basics • .NET basics Tools Required • The CLR (Common Language Runtime) should be running on the machine • Csc.exe – the C# compiler which is supplied standalone with the .NET Framework SDK or with Visual Studio.NET. Common Concepts Creating Web Services is the key to a programmable Web. The .NET platform provides a rich framework for building and using these services – using a programming abstraction. The resulting model is both scalable and extensible – and embraces open Internet standards (HTTP, XML, SOAP, SDL) so that services can be accessed and consumed from any client or Internet enabled device. What is a Web Service? • A Web Service is a programmable URI (universal resource identifier) • A Web Service provides a way for exposing/accessing building blocks for applications and services over the web. Web request for the Web Service URL: http://webserver/webservice/helloworld.asmx/SayHello?s=Hello+World
Figure 1: Web Service Request Benefits of Web Services: • Enables simpler data communication between systems. • Enables developers to expose programmatic functionality to web clients without requiring knowledge of HTTP or Type Marshalling • Adds another choice to “Build or buy” development solutions • Faciliates B2B (Business to Business) Communication • New services/new revenue streams Scenarios Business to Business • A. Datum Corporation provides a web services for obtaining real-enough time stock quotes. Any web site or client app, anywhere in the world, can use this interface to add stock quotes to their application. • Arbor Shoes does business with a number of shoe vendors. Each shoe vendor provides a web service for checking accounts, checking shipments, and ordering more shoes. This usage of web services replaces private networks, or even paper forms, for doing private business-to-business communications. A key requirement is that the communications must be secure (both authenticated and encrypted). • Passport provides a unified user name and password service – enabling sites to avoid writing code for logins. This usage of web services provides for the service model for software, rather than shrink-wrap. Key requirements include security, and the ability to bill for service usage.
Client/Server • Southwest Financial Services provides a website for trading stocks. They also provide a highly interactive version, based on ActiveX controls hosted within the browser. These ActiveX controls could be housed in a Windows application, or as a safe-to-download WinForms application. In all of these scenarios, Southwest Financial Services should be using Web Service calls from the ActiveX controls to communicate with the web server to receive and send information in a stateless, scalable manner.
Standards Support • HTTP - The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. It is a generic, stateless, protocol which can be used for many tasks beyond its use for hypertext, such as name servers and distributed object management systems, through extension of its request methods, error codes and headers • XML - The eXtensible Markup Language (XML) is a way of describing data description languages in a consistent syntax. • SOAP (Simple Object Access Protocol) - SOAP is a lightweight protocol for exchange of information in decentralized, distributed environments. It is an XML based protocol that consists of two parts: an envelope for handling extensibility and modularity and an encoding mechanism for representing types within the envelope. • SCL (Service Contract Language) - a XML format for describing contracts between a set of endpoints exchanging messages. • SDL (Service Discovery Language) - an XML-based grammar for describing the capabilities of Web Services Creating the “Hello World” Web Service First we’ll take a look at creating a “Hello World” Web Service. “Hello World” will take a string as an argument and return the string embedded in XML to client requests. By creating a Web Service, we will expose our functionality through XML and HTTP. The 1_HelloWorld directory contains C# source code for HelloWorld.asmx (Web Services use the extension ASMX).
1. Using Explorer, create a directory named Test. 2. Using Internet Services Managed, create a web called Test that maps to your Test directory (see Figure 2). Figure 2: Test Virtual Directory 3. Create a subdirectory beneath your Test directory and name it WSHelloWorld. 4. Create a new text file named HelloWorld.asmx in your WSHelloWorlddirectory. 5. Using a text editor, add a WebService page directive and set the language to C#. <%@ WebService Language="C#" Class="HelloWorld" %> HelloWorld.asmx is your Web Service page. In this exercise you will write code directly in the class, however, you could also create a “codebehind” which is what Visual Studio does for us. A codebehind separates you base pages (ASMX in this case) from your programming logic. The codebehind gets compiled into an Assembly. 6. Reference the Web Services namespace using System.Web.Services; 7. Create your class (if you need the ASP.NET Intrinsics, your class needs to inherit from WebService). public class HelloWorld { } 8. Create the SayHello method and mark it with the WebMethod attribute. [WebMethod] public string SayHello (string s){ return s; } Your final code looks like the following: <%@ WebService Language="C#" Class="HelloWorld" %> using System.Web.Services; public class HelloWorld { [WebMethod] public string SayHello(string s){ return s; } }
Testing “Hello World” Web Service The .NET Framework provides a built-in way to test our new Web Service. 1. Browse to your Web Service: http:///Test/WSHelloWorld/HelloWorld.asmx 2. Enter a test value for the Web Service parameter and click Invoke (see Figure 3). In this case, s is the parameter and you will supply the value Hello World. Figure 3: Invoking SayHello Web Method
3. The Web Service produces the following XML response: Hello World
Note that the request was submitted as an HTTP GET request. The full request submitted when you clicked invoke was: http:///Test/WSHelloWorld/HelloWorld.asmx/SayHello?s=Hello+World Publishing “Hello World” Web Service In order to allow others to write code against your Web Service, you need to provide a contract. SDL (Service Description) provides this contract. Note – SDL will be upgraded to WSDL (Web Service Contract Language) in the future. SDL is basically an XML document that describes the following characteristics of your Web Service: • Service Transports • Invocation Semantics • Call Sequence The service transports are the protocols and their end-points. Invocation semantics define how requests are made to the service. Call sequence defines how a client and server communicate for a request, such as SOAP, HTTP GET or HTTP POST.
You generate SDL using one of the following methods: • Manually • WebServiceUtil.exe • Automatically Generating SDL manually is not recommended because it’s a mundane task that’s easily automated for you. WebServiceUtil.exe (provided with the .NET SDK) provides command line arguments for generating SDL. To view the commands, run WebServiceUtil.exe with a /? argument.
Automatic generation of SDL is simple and preferred. To generate SDL automatically, do one of the following: • Browse to your Web Service and click the SDL link • Browse to your Web Service and append SDL to the QueryString (see Figure 4)
Figure 4: Generating SDL Automatically
One benefit of generating SDL is that it provides a means for strong typing since we know the data types before we use them. You can also think of SDL as IDL (Interface Definition Language) for your Web Service. Calling the “Hello World” Web Service To call a Web Service, you can use one of three supported protocols: • HTTP-GET • HTTP-POST • SOAP
The SDL file generated by your Web Service defines invocation semantics for all three protocols. GET and POST are standard HTTP methods for passing name/value pairs to a Web server. SOAP uses POST but defines a standard format for calling and serializing more complex data using XML and HTTP. HTTP-GET You already used HTTP-GET to call the “Hello World” Web Service when you invoked the SayHello method from the Web Service test page. HTTP-GET uses the HTTP Get verb to send data to the Web server using name/value pairs in the form of a QueryString. Let’s look at an example: http://MyWebServer/Test/WSHelloWorld/HelloWorld.asmx/SayHello?s=Hello+World In this case, http://MyWebServer/Test/WSHelloWorld/HelloWord.asmx is the base URL. ?s=Hello+World is the QueryString. s is the named parameter and Hello+World is the value. HTTP-POST HTTP-POST is similar to HTTP-GET in that name value pairs are passed to the Web server. However, rather than use the QueryString, the data is sent in the body of the request. SOAP SOAP defines the call format using XML and HTTP as its transport. SOAP, in addition to supporting richer data types, standardizes call formats. A SOAP message consists of three parts: 1. Envelope 2. Encoding Rules 3. Remote Procedure Calls The Envelope uses XML to describe the message being sent. The encoding rules specify how the data needs to be serialized. The remote procedure calls section supports the description of RPCs and their responses. For our sample, you will create a client proxy, which will use SOAP for the method invocation. You can generate your client proxy from the SDL that you generated above using WebServiceUtil.exe. The 2_MakeClientProxy directory includes the SDL, proxy source, and commands for generating a client proxy. From a command prompt, issue the following command: (makeproxy.bat) webserviceutil.exe /command:proxy /path:HelloWorld.sdl /language:c# /namespace:HelloWorld /out:HelloWorldProxy.cs Next, compile your proxy source: (buildproxysrc.bat) csc /target:library /out:HelloWorldProxy.dll /r:system.web.services.dll /r:system.xml.serialization.dll HelloWorldProxy.cs
Compiling your source produces the HelloWorldProxy.dll assembly. Important – you need to place HelloWorldProxy.dll in your \bin directory beneath your Web root, so that it will be accessible from your ASP.NET pages. You can confirm that your assembly is valid by opening it up in ILDASM.Exe and checking the metadata. If our assembly is valid, you can now use it like any other .NET component.
The following sample calls our proxy from an ASP.NET page client, invoking our SayHello method:
4_C#Client contains a sample calling your proxy object from a C# client. Important – when you create the C# client, keep it simple by placing the HelloWorld.dll assembly in the same directory (see the documentation for how the runtime resolves referenced assemblies). The following code is a C# sample calling your proxy and invoking the SayHello method: using System; using HelloWorld; using System.Web.Services; using System.Xml.Serialization;
public class MyHelloWorld{ public static void Main(){ string s=""; HelloWorld.HelloWorld ws = new HelloWorld.HelloWorld(); for(int i=0; i < 10; i++){ s = ws.SayHello("Hello World"); } Console.WriteLine(s); Console.ReadLine(); } }
Exercise: At this point, you’ve seen how to create a Web Service, test a Web Service, publish a Web Service and call a Web Service. Before walking through the anatomy of a Web Service, be sure that you can successfully create and call a Web Service. Working code is provided in the directories accompanying this tutorial, however it is to be used as a reference point. Your server name will be different from the sample code provided, so you need to write code and generate appropriate SDL for your Web server. Anatomy of a Web Service Request Let’s walk through what happens when we request our Web Service from a browser: 1. A POST request is submitted to Hello World Web Service http://RemoteWebServer/test/wsHelloWorld/HelloWorld.asmx Content Type is set to text/xml The following HTTP Undocumented Header is sent: SOAPAction: http://tempuri.org/SayHello 2. The Web server sends a response to the client returning a status code of 64, continue. 3. The XML request is sent to the Web Service
Hello.World
Here we see that Hello World is passed to the SayHello method wrapped in XML:
Hello World 4. The Web server sends a response to the client setting the Content-Type to text/xml 5. The XML response is sent to the client:
Hello.World
Exercise: Trace a Web Service request using Network Monitor. Note Network Monitor is available through either the Windows 2000 Server installation or by installing Systems Management Server. Data Types Supported HTTP-Get and POST support only primitves (int, string …etc), enums, and arrays of primitives. SOAP, in addition to enabling passing complex data types, also standardizes the call formats.
Type Description SOAP POST GET Primitive Types Standard primitive types: String, Int32, Byte, Boolean, Int16, Int64, Single, Double, Decimal, DateTime, and XmlQualifiedName Yes Yes Yes Enum Types Enumeration types Yes Yes Yes Arrays of Primitives, Enums Arrays of primitives such as string[] and int[] Yes Yes Yes Classes and Structs Class and struct types with public fields or properties. The public properties and fields are serialized Yes No No Arrays of Classes (structs) Arrays of classes and structs Yes No No XmlNode Yes No No Arrays of XmlNode Yes No No
The key points to remember are: • GET and POST only support the most basic data types passed as name/value pairs • SOAP supports rich data types by packaging the data in XML and standardizing a call format
Exercise: Can you pass an array of structs? Sure you can, but give it a try. Source code is available in 5_ArrayOfStructs. For extra credit, test returning other data formats such as using an ADO.NET DataSet. ASP.NET Services Web Services have access to ASP.NET services. This includes Application state, Session state, caching, security …etc. To access the ASP.NET services, your class needs to inherit from WebService: public class HelloWorld : WebService { Session State Session state provides a way to automatically identify and classify requests coming from a single browser client into a logical application “session” on the Web server. Session data can be accessed across multiple browser requests. However, just because you can do something, does not mean that you should. Sessions are overhead to an application. You can disable Sessions on a per WebMethod basis, conserving system resources: [WebMethod(EnableSession=false)] The 6_ASP.NETServices directory contains a Web Service sample that writes out the current Session ID number. Here is the code it contains:
<%@ WebService Language="C#" Class="SessionState" %> using System; using System.Web.Services; public class SessionState : WebService{ [WebMethod(EnableSession=true)] public string GetSession(){ return "Your SessionId is: " + Session.SessionID; } } Note that Session state is disabled for Web Services by default to improve scalability. Setting EnableSession=true, enables the use of Sessions from the Web Service. Application State Application state allows developers to share global information throughout an ASP.NET application. An ASP.NET application is defined as the sum of all files, pages, handlers, modules, and code that can be invoked through the scope of a given virtual directory. You can use Application state from your Web Service as you would in an ASP.NET page. Transactions Transactions can be enabled on a per WebMethod basis: [WebMethod(TransactionMode=TransactionMode.RequiresNew)]
Exercise: • Disable cookies on your browser and see how the Session ID number is affected on multiple requests. • Set a counter in Application state and increment it through your Web Service on each request. • Try using ASP.NET fragment caching from a Web Service. (For information on Fragment Caching, see the documentation and the ASP.NET QuickStart) Summary • Web Services rock!
Food for Thought • What makes a good Web Service? • What does a client need to early bind to a Web Service? • What acts as a contract defining a Web Service’s public methods? • How do you determine which method is used (post, get, soap) against a web service? • How do activation, lifetime, and events come into play with a Web Service? • Do ASP Sessions get created when you call a Web Service by default? • How does a Web Service distinguish a request from one client from another? APPENDIX A: Web Service Scenarios The following list is a highlight of some of the scenarios the MSDN architecture team brainstormed when considering how Web Services fit into various business models. This list is simply provided to help you kick-start thinking how you might apply Web Services to solve some of your business problems:
Financial Services • Access to bank accounts • Bill Payment • Portfolio management • Stock quotes • Financial planning • Calculators (e.g. when can I retire?) • Research queries • Chart Service (for clients that can’t generate charts from XML, the chart needs to be generated on the server)
Travel Industry • Make reservations • Check availability • Check prices • Locate related services for trip • Check flight status/location (real-time tracking) • Map Service (get a map of any location) • Use frequent flyer services • Credit card authorization
Shipping Company/Delivery Service • Rate calculator • Schedule pickup • Track packages • Locate drop off center • Track location of delivery trucks/planes (real-time tracking) • Resource scheduling (e.g. figure out how to optimize use of people/vehicles to make deliveries) • Compute GPS location from street address • Map Service (get a map of any location)
Virtual Shopping Mall • Cross store shopping cart • Credit card authorization
Newspaper • News Headlines (subscribe to categories of interest) • Retrieve news articles • Comics server • Classified ads • Credit card authorization
Drug Store • Query for information • Catalog search • Shopping cart • Refill prescription • Check availability • Suggest alternatives • Credit card authorization
Concierge Service • All the connections to business partners • Resource scheduling (e.g. figure out how to optimize use of people/vehicles to run errands, make deliveries) • Shopping cart • Track location of deliveries, status of errands (real-time tracking) • Personal Calendar (ala schedule+ but on the web) • Credit card authorization • Compute GPS location from street address • Map Service (get a map of any location)
Entertainment Portal • Query reviews • Query schedules • Purchase tickets • Purchase CD/DVD • Query for recommendations • Purchase PPV event • Control home DVR • Discussion forums (threaded message board) • Credit card authorization
Post Office • Rate calculator • Track packages • Locate post office or street-side box • Validate address • Process address change • Hold or resume mail delivery • Track location of delivery trucks/planes (real-time tracking) • Resource scheduling (e.g. figure out how to optimize use of people/vehicles to make deliveries) • Compute GPS location from street address • Map Service (get a map of any location)
Utility Companies • Query account status • Query historical account data • Compute expected costs • Pay bills (direct debit or credit card)
E-Book Store • Catalog search • Book price quote service • Query reviews/ratings • Query recommendations • Purchase and download title • Discussion forums (threaded message board) • Credit card authorization
Personal Portal • Access to bank accounts • Portfolio management • Stock quotes • View travel itineraries • Check flight status/location • Track packages • Display status of orders from multiple stores • Build a wish-list of items you want from multiple stores • News headlines • Sports scores • Today’s comics • TV Schedule (local/satellite) • Movie schedules and ticket purchase • Upcoming concerts and ticket purchase • Remotely monitor home security status • Discussion forums (threaded message board) • Personal Calendar (ala schedule+ but on the web) • Traffic/transit status (ala www.smarttrek.org) • Compute GPS location from street address • Find restaurant, etc. close to my current location • Map Service (get a map of any location) • Credit card authorization • Bill paying • Weather Report • Check for updated virus detection signature files • Monitor EBAY auction status • Request taxi at current location • Translation Service (ala AltaVista Babel Fish) APPENDIX B: WebServiceUtil WebServiceUtil.exe WebServiceUtil.exe is a command-line utility installed with the .NET SDK. You can use it to generate the following: • SDL • Proxy source for creating client components
For most current syntax, run WebServiceUtil.exe with a /? parameter. Syntax WebServiceUtil /command:proxy /path: [/language:] [/namespace:] [/out:] [/xsd: [...]] WebServiceUtil /command:template /path: [/language:] [/namespace:] [/out:] [/xsd: [...]] WebServiceUtil /command:makeSDL /baseurl: /assembly: [/out:] WebServiceUtil /command:getSDL /url: [/out:]
Option Description getSDL Get a service description file from a URL and saves it to a local directory. makeSDL Create static service description files for web services in an assembly. proxy Create source code for a proxy (web service client) class from a Service Description Language (SDL) file or assembly. The Service Description Language (SDL) is an XML grammar that developers and development tools can use to represent the capabilities of a Web Service. template Create source code for a template (web service server) class from an SDL file. /assembly: Short form: /a: The name of an assembly containing web services. /baseurl: Short form: /b: The base URL to the web service. /command: Short form: /c: The command to perform upon the specified path, XSD, or URI. /language: Short form: /l: The language to use for the generated proxy class. Choose from C#, Visual Basic, JScript, or any language with a supplied CodeGenerator. The default language is C#. /namespace: Short form: /n: The namespace for the generated proxy or template. The default namespace is the global namespace. /out: Short form: /o: The location at which to create files. The default output location is the current directory. /path: Short form: /pa: A local path to a service description file, or a URI that the service description file was retrieved from. /url: Short form: /u: A URL to a specific file. /xsd:,<...> Short form: /x:,<...> One or more local XML schema files. Filenames must end in .xsd.
Samples • Retrieving SDL from a remote server: webserviceutil /command:getSDL /url:http://RemoteWebServer/test/wshelloworld/helloworld.asmx?sdl • Creating proxy source from a remote server: webserviceutil /command:proxy /path:http://RemoteWebServer/test/wshelloworld/helloworld.asmx /out:HelloWorld.cs /language:c# Additional Resources • See Web Service walkthroughs in the Visual Studio documentation • See Web Services in the .NET SDK Documentation • MSDN: http://msdn.microsoft.com • The Programmable Web: Web Services Provides Building Blocks for the MS .NET Framework: http://msdn.microsoft.com/msdnmag/issues/0900/WebPlatform/WebPlatform.asp
|
Responses
|
| Author: Shyni 31 May 2008 | Member Level: Gold Points : 2 | This is great Information, Thanks for your effort to share it with everyone.
|
|
|