Creating Web Services


Creating a Web Service in Visual Studio 2005 is as simple as picking the Web Service template when adding a new item. If you don't use code behind, then you will have a file created containing the code shown in Listing 16.1. There are several important points to notice about the created file:

  • The file suffix is ASMX, as opposed to ASPX for ASP.NET pages

  • The use of the WebService page directive, to indicate that this is a Web Service

  • The inclusion of namespaces System.Web.Services and System.Web.Services.Protocols

  • The use of attributes on the class and methods

We'll be describing these attributes in more detail as we go through the section.

If you use code behind, then two files are created. The first is the ASMX file, which consists only of the WebService directive. The second is a class file in the App_Code folder, containing the code for the server. This is the same code as shown in Listing 16.1, with the addition of a public constructor. It is important to note that because Web Services provide program-to-program communication, there is no user interface; the ASMX file is simply the ASP.NET way of exposing the underlying code. ASP.NET can generate a user interface for Web Services, but this isn't a part of the Web Service itself. You'll see how one is created, and how it can be controlled, a little later.

Listing 16.1. The Default Web Service Code

<%@ WebService Language="C#"  %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService  : System.Web.Services.WebService {     [WebMethod]     public string HelloWorld() {         return "Hello World";     } }

What you put into the Web Service is simply the methods you wish to expose. For example, the default code template contains a method called HelloWorld that returns a string. You can have both methods that return data and methods that accept data, much as you do in existing code. For example, consider Listing 16.2, which shows two simple methods, the first to fetch the shippers from the Northwind database, the second to insert a new shipper.

Listing 16.2. Web Service Methods that Return and Accept Data

[WebMethod] public DataSet GetShippers() {   DataSet ds = new DataSet();   ds.Merge(ShipperDataLayer.GetShippers());   return ds; } [WebMethod] public int InsertShipper(string CompanyName, string Phone) {   int ShipperID = -1;   ShipperDataLayer.Insert(CompanyName, Phone, ref ShipperID);   return ShipperID; }

The only thing that differentiates these methods from other methods is that they are attributed, to indicate they are exposable as methods of a Web Service. The methods can be used internally, without making a Web Service call, so you can have a single method serve two purposes. You may, however, wish to abstract the Web Service interface so that changes to the underlying data or business classes do not affect the exposed Web Service methods. Web Service methods should be instance methods, and not static.

Web Service Attributes

There are several areas where attributes can be used in Web Services, some of which will be covered in the Data Transfer section later in the chapter. The minimum requirement is for the class and methods to have attributes. For the class, you use two attributes, the first of which is WebService, which indicates that this class is a Web Service. There are three properties of the WebService attribute:

  • Description, a textual description of the service

  • Name, the name of the Web Service, which defaults to the class name

  • Namespace, the unique identifier for the service, often the company Web site URL. Namespaces in Web Services aren't the same thing as namespaces in code files

For example:

[WebService(Namespace = "http://northwind.org/services/",   Description = "Web Services supplied by Northwind Traders")] public class WebService  : System.Web.Services.WebService {


The WebServiceBinding defines the set of operations supported by the Web Service. The supported properties are:

  • ConformsTo, used to specify that the Web Service will conform to a known set of standards, in this case those defined by the WS-I Basic 1.1 standard, which defines things such as the supported version of XML, XML Schema, UDDI, and so on. The only supported conformance claim at the current time is WsiProfiles.BasicProfile1_1, which indicates WS-I 1.1 Basic conformance. Note that this uses SOAP 1.1, and not SOAP 1.2, because SOAP 1.2 is not part of the WS-I Basic Profile 1.1

  • EmitConformanceClaims, which defines whether or not document elements are emitted in the WSDL, indicating that the service conforms to WS-I Basic Profile 1.1

  • Location, which defines the location for the binding of the Web Service and defaults to the URL of the service

  • Name, which defines the name of the binding and defaults to the name of the service with Soap appended

  • Namespace, which defines the namespace for the binding

For example:

[WebService(Namespace = "http://northwind.org/services/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1,   EmitConformanceClaims = true)] public class WebService : System.Web.Services.WebService {


For Web methods, you use the WebMethod on each method that you wish to expose. The Web Service can use other methods internally, but if they are not attributed they won't be exposed outside of the class. The WebMethod attribute has six properties:

  • BufferResponse, which enables buffering of responses. The default value of true ensures that the results are sent in one step to the client

  • CacheDuration, which is the number of seconds for which to cache the results of the method call. The default value of 0 indicates no caching. Methods with parameters will be cached based upon the parameter value

  • Description, which is a textual description of the Web Service

  • EnableSession, which enables session state for the method. The default value is false

  • MessageName, which is a unique name for the method that is useful when you have overloaded methods. However, overloaded methods are not valid for the WS-I Basic Profile, even when using different message names, so you should use unique methods if conformance is required. If conformance is not an issue, then you can change the ConformsTo property of the WebService attribute to WsiProfiles.None

  • transactionOption, which indicates whether or not the method participates in a root level transactionthat is, whether it starts a transaction (transactions cannot be started by another application and flow into the Web Service). The value can be one of the transactionOption values, but these behave slightly differently than normal. A Web method either does not participate in a transaction (where you would use Disabled, NotSupported, or Supported), or it does participate in a transaction (and you use Required or RequiresNew)

For example:

[WebMethod(CacheDuration = 60,   Description = "Returns all of the Shippers")] public DataSet GetShippers()


Testing Web Services

You can test your Web Services by navigating to the ASMX file. For example, consider Figure 16.1, which shows the results of navigating to the Northwind Web Service shown in Listing 16.2. Since Web Services have no user interface, ASP.NET has an HTTP Handler that accepts requests for the ASMX file and dynamically generates a help page. The figure shows the two methods within the Web Service and contains a lengthy description about the default namespace. This description is present because the namespace has been left at the default created by Visual Studio 2005, which is http://tempura.org/. If you change the namespace, perhaps to http://northwind.org/services/, then the description disappears and you only see the supported operations.

Figure 16.1. The ASP.NETWeb Service Help page


To test the methods in the Web Service, you can click them; you'll then see details about the method, such as the protocols supported, and a button to test the method.

Testing a Method that Returns Data

For a method that has no parameters, you see something like Figure 16.2, with an Invoke button to invoke the Web Service method. The content underneath this button describes the request and response formats for SOAP 1.1, SOAP 1.2, and HTTP POST.

Figure 16.2. Testing a Web Service method without parameters


Clicking the Invoke button will run the Web Service, which will return the XML results. For the GetShippers method, the results are shown here. You can see that there is an inline schema as well as the data, which allows consumers of the data to understand the data structure.

<?xml version="1.0" encoding="utf-8"?> <DataTable xmlns="http://northwind.org/services/">   <xs:schema  xmlns=""     xmlns:xs="http://www.w3.org/2001/XMLSchema"     xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">     <xs:element name="NewDataSet" msdata:IsDataSet="true"       msdata:MainDataTable="Shippers"       msdata:UseCurrentLocale="true">       <xs:complexType>         <xs:choice minOccurs="0" maxOccurs="unbounded">           <xs:element name="Shippers">             <xs:complexType>               <xs:sequence>                 <xs:element name="ShipperID"                   msdata:ReadOnly="true"                   msdata:AutoIncrement="true" type="xs:int" />                 <xs:element name="CompanyName">                   <xs:simpleType>                     <xs:restriction base="xs:string">                       <xs:maxLength value="40" />                     </xs:restriction>                   </xs:simpleType>                 </xs:element>                 <xs:element name="Phone" minOccurs="0">                   <xs:simpleType>                     <xs:restriction base="xs:string">                       <xs:maxLength value="24" />                     </xs:restriction>                   </xs:simpleType>                 </xs:element>               </xs:sequence>             </xs:complexType>           </xs:element>         </xs:choice>       </xs:complexType>     </xs:element>   </xs:schema>   <diffgr:diffgram     xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"     xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">     <DocumentElement xmlns="">       <Shippers diffgr: msdata:rowOrder="0">         <ShipperID>1</ShipperID>         <CompanyName>Speedy Express</CompanyName>         <Phone>(503) 555-9831</Phone>       </Shippers>       <Shippers diffgr: msdata:rowOrder="1">         <ShipperID>2</ShipperID>         <CompanyName>United Package</CompanyName>         <Phone>(503) 555-3199</Phone>       </Shippers>       <Shippers diffgr: msdata:rowOrder="2">         <ShipperID>3</ShipperID>         <CompanyName>Federal Shipping</CompanyName>         <Phone>(503) 555-9931</Phone>       </Shippers>     </DocumentElement>   </diffgr:diffgram> </DataTable>


Testing a Method that Accepts Data

For a method with parameters, a form allowing entry for the parameter values is dynamically generated. The parameter values will be passed to the Web Service method when the Invoke button is clicked.

Figure 16.3. Testing a Web Service method with parameters


Caching and State

Caching within Web Services can be achieved using the methods described in Chapter 6, and should be done at the data layer or service layer, depending upon your needs. SQL Server notifications cannot be used, because they require an open connection, but this is no loss since one of the main points of Web Services is to provide loosely coupled applications. Notifications are designed for tightly coupled systems.

Although Web Services are stateless, they do have access to the Application and Session objects for state storage and are able to access the HTTP context to use the Cache object.

Creating Asynchronous Web Services

In Chapter 5 you saw that asynchronous operation can improve the performance of Web sites, and this is true in Web Services, especially remote ones. Web Services can be accessed locally without having to create a Web Reference in Visual Studio 2005, but this only gives you access to the methods exposed by the service, or the base class, WebService. If you use the Add Web Reference to add a reference, then a proxy class is created for you that gives you access to the asynchronous methods. You can, of course, implement the asynchronous pattern yourself, but the proxy generation will do this for you.

If you need to manually create a proxy for others to use, you can use the WSDL tool, found in the framework directory. There are a number of options, but to create the proxy class you simply need to supply the URL of the Web Service, as shown here:

wsdl.exe http://localhost/illustrated/ch16/Northwind.asmx


This will generate a source code file called Northwind.cs that contains the proxy code.



ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net