Recipe 14.2. Creating a Web Service


Problem

You want to create your own web service.

Solution

Use Visual Studio 2005 to create a new web service and then add methods to expose the functionality required for your web service.

To create the new web service:

  1. On the Visual Studio 2005 File menu, choose New Web Site….

  2. Right-click on the new web site in the Solution Explorer, select Add New Item, and select the Web Service template.

  3. Enter the name of the web service in the Name text box, select the desired language, and click Add.

Visual Studio 2005 creates a folder for the web site that contains an .asmx file and code-behind files for the web service, like those shown in Examples 14-2, 14-3, 14-4 through 14-5. The web service is fully functional at this point but is a shell with no useful functionality.

Visual Studio 2005 places the code-behind files for web services in the App_Code directory instead of placing them in the same folder as the .asmx file, as Visual Studio 2003 did.


You need to add methods to the code-behind to expose the functionality required for your web service. The code-behind shown in Examples 14-6 (VB) and 14-7 (C#) shows a method we have added to our example web service to return a list of books from a database.

You can add a web service to an existing web application by selecting the web site in the Solution Explorer and then selecting Add New Item from the Website menu. When the Add New Item dialog box is displayed, select the Web Service template, enter the desired name of the web service, enter the desired language, and click Add. Any number of web services can be added to a web application.


Discussion

Web services are a useful tool for communicating with remote systems or with systems built with technologies different from those used to build your application.

Web services are convenient for wrapping legacy COM components. This is especially true when you need to access the functionality of those components from a different domain than where the components reside and the domains do not have a trust relationship.


Visual Studio 2005 simplifies the creation of web services. With a few menu selections, you can quickly build a web service shell that you can use to create the functionality required by your application.

In ASP.NET, a web service consists of an .asmx file and a code-behind class that provides the required functionality. The content of an .asmx file consists of a single line that contains a WebService directive. The line is like the @ Page directive used in the .aspx file but with Page replaced by WebService:

 

<%@ WebService Language="VB" CodeBehind="~/App_Code/CH14QuickWebServiceVB1.vb" %>

<%@ WebService Language="C#" CodeBehind="~/App_Code/CH14QuickWebServiceCS1.cs" %>

The code-behind file for a web service consists of a class that inherits from System.Web.Services.WebService.

 

Public Class CH14QuickWebServiceVB1 Inherits System.Web.Services.WebService … End Class 'CH14QuickWebServiceVB1

public class CH14QuickWebServiceCS1 : System.Web.Services.WebService { … } // CH14QuickWebServiceCS1

In addition, Visual Studio 2005 adds a WebService attribute to the class definition. Though not explicitly required, the WebService attribute lets you define the namespace for the web service. By default, the namespace is set to http://tempuri.org/, but you will typically want to set this to the URI representing your company, such as http://www.dominiondigital.com/.

 

<WebService(Namespace:="http://www.dominiondigital.com/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ Public Class CH14QuickWebServiceVB1 Inherits System.Web.Services.WebService … End Class 'CH14QuickWebServiceVB1

[WebService(Namespace = "http://www.dominiondigital.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class CH14QuickWebServiceCS1 : System.Web.Services.WebService { … } // CH14QuickWebServiceCS1

Visual Studio 2005 automatically adds a WebServiceBinding attribute to web service classes, as shown previously. This attribute indicates that the web service conforms to the Web Services Interoperability Basic Profile specification (WS-I BP 1.1). For more information on the web services interoperability, see http://www.ws-i.org.


To add useful functionality to the web service, you create methods as you would for any other class, except that you precede each method definition with a WebMethod attribute. The WebMethod attribute informs Visual Studio 2005 the method is to be exposed as part of the web service.

For instance, the getBookList method shown in our example queries a database for a list of books and returns the list in a DataSet. The number of books retrieved is defined by the numberOfBooks parameter. Nothing special is done in the code to support the web service. Visual Studio 2005 and the .NET Framework take care of the creation of the XML and the SOAP wrapper used to transfer the data to the client.

One of the big advantages to creating web services with Visual Studio 2005 and ASP.NET is the testing and debugging functionality provided. ASP.NET provides a series of web pages that create a test harness that can be used to test all the exposed methods of the web service. Visual Studio 2005 lets you set breakpoints in your web service code so you can step through it to verify its operation.

The test harness created by Visual Studio 2005 can be used only if your web methods use .NET data types for the passed parameters.


To test a web service, run your project in Visual Studio 2005 in debug mode and access the .asmx file for the web service. ASP.NET will display a page listing all of the methods exposed by the web service, as shown in Figure 14-1.

Figure 14-1. Methods exposed by the web service


In this example, clicking on the getBookList method displays another page where you can enter the required numberOfBooks parameter value and invoke (execute) the method. Though not shown in Figure 14-2, this page displays the content of the XML-encoded request and response messages for the method using SOAP, Http Get, and Http Post. These samples allow you to examine the data that is exchanged when the method is called.

Figure 14-2. Invoking the method


When you click the Invoke button, ASP.NET generates an Http Get request and submits it to the web service. The web service responds with an Http response containing the requested data. In our example, the XML shown in Example 14-1 is returned from the web service when the numberOfBooks parameter is set to 10.

See Also

http://www.ws-i.org for information on Web Service Interoperability

Example 14-1. XML returned with numberOfBooks parameter set to 10

 <?xml version="1.0" encoding="utf-8"?> <DataSet xmlns="http://www.dominiondigital.com/"> <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:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Table"> <xs:complexType> <xs:sequence> <xs:element name="Title" type="xs:string" minOccurs="0"/> <xs:element name="ISBN" type="xs:string" minOccurs="0"/> <xs:element name="Publisher" type="xs:string" minOccurs="0"/> </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"> <NewDataSet xmlns=""> <Table diffgr: msdata:rowOrder="0"> <Title>.Net Framework Essentials</Title> <ISBN>0-596-00302-1</ISBN> <Publisher>O'Reilly</Publisher> </Table> <Table diffgr: msdata:rowOrder="1"> <Title>Access Cookbook</Title> <ISBN>0-596-00084-7</ISBN> <Publisher>O'Reilly</Publisher> </Table> … <Table diffgr: msdata:rowOrder="9"> <Title>Developing ASP Components</Title> <ISBN>1-565-92750-8</ISBN> <Publisher>O'Reilly</Publisher> </Table> </NewDataSet> </diffgr:diffgram> </DataSet> 

Example 14-2. Quick web service .asmx file (.vb)

 <%@ WebService Language="VB" CodeBehind="~/App_Code/CH14QuickWebServiceVB1.vb"  %> 

Example 14-3. Quick web service code-behind (.vb)

 Option Explicit On Option Strict On Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols Namespace VBWebServices ''' <summary> ''' This class provides the code-behind for CH14QuickWebServiceVB1.asmx ''' </summary> <WebService(Namespace:="http://www.dominiondigital.com/")> _  <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ Public Class CH14QuickWebServiceVB1 Inherits System.Web.Services.WebService Public Sub CH11QuickWebServiceVB1() End Sub <WebMethod()> _ Public Function HelloWorld() As String Return "Hello World" End Function End Class 'CH14QuickWebServiceVB1 End Namespace 

Example 14-4. Quick web service .asmx file (.cs)

 <%@ WebService Language="C#" CodeBehind="~/App_Code/CH14QuickWebServiceCS1.cs"  %> 

Example 14-5. Quick web service code-behind (.cs)

 using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; namespace CSWebServices { /// <summary> /// This class provides the code-behind for CH14QuickWebServiceCS1.asmx /// </summary> [WebService(Namespace = "http://www.dominiondigital.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class CH14QuickWebServiceCS1 : System.Web.Services.WebService { public CH14QuickWebServiceCS1() { } [WebMethod] public string HelloWorld() { return "Hello World"; } } // CH14QuickWebServiceCS1 } 

Example 14-6. Code-behind with method for obtaining a list of books (.vb)

 Option Explicit On Option Strict On Imports System.Configuration Imports System.Data Imports System.Data.OleDb Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols Namespace VBWebServices ''' <summary> ''' This class provides the code-behind for CH14QuickWebServiceVB2.asmx ''' </summary> <WebService(Namespace:="http://www.dominiondigital.com/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ Public Class CH14QuickWebServiceVB2 Inherits System.Web.Services.WebService '''*********************************************************************** ''' <summary> ''' This routine gets the list of books from the database. ''' </summary> ''' ''' <param name="numberOfBooks">Set to the number of books to retrieve ''' </param> ''' <returns>DataSet containing the list of books</returns> <WebMethod()> _ Function getBookList(ByVal numberOfBooks As Integer) As DataSet Dim dbConn As OleDbConnection = Nothing Dim da As OleDbDataAdapter = Nothing Dim dSet As DataSet = Nothing Dim cmdText As String Dim strSQL As String Try 'get the connection string from web.config and open a connection 'to the database cmdText = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dbConn = New OleDbConnection(cmdText) dbConn.Open() 'build the query string used to get the data from the database strSQL = "SELECT Top " & numberOfBooks.ToString() & " " & _  "Title, ISBN, Publisher " & _  "FROM Book " & _  "ORDER BY Title" 'create a new dataset and fill it with the book data dSet = New DataSet da = New OleDbDataAdapter(strSQL, dbConn) da.Fill(dSet) 'return the list of books Return (dSet) Finally 'clean up If (Not IsNothing(dbConn)) Then dbConn.Close() End If End Try End Function 'getBookList End Class 'CH14QuickWebServiceVB2 End Namespace 

Example 14-7. Code-behind with method for obtaining a list of books (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Web; using System.Web.Services; namespace CSWebServices { /// <summary> /// This module provides the code behind for the CH14QuickWebServiceCS2.asmx /// </summary> [WebService(Namespace = "http://www.dominiondigital.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class CH14QuickWebServiceCS2 : System.Web.Services.WebService { ///*********************************************************************** /// <summary> /// This routine gets the list of books from the database. /// </summary> /// /// <param name="numberOfBooks">Set to the number of books to retrieve /// </param> /// <returns>DataSet containing the list of books</returns> [WebMethod] public DataSet getBookList(int numberOfBooks) { OleDbConnection dbConn = null; OleDbDataAdapter da = null; DataSet dSet = null; String connectionStr = null; String cmdText = null; try { // get the connection string from web.config and open a connection // to the database connectionStr = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dbConn = new OleDbConnection(connectionStr); dbConn.Open(); //build the query string used to get the data from the database cmdText = "SELECT Top " + numberOfBooks.ToString() + " " +   "Title, ISBN, Publisher " +   "FROM Book " +   "ORDER BY Title"; // create a new dataset and fill it with the book data dSet = new DataSet(); da = new OleDbDataAdapter(cmdText, dbConn); da.Fill(dSet); //return the list of books return (dSet); } // try finally { // cleanup if (dbConn != null) { dbConn.Close(); } } // finally } // getBookList } // CH14QuickWebServiceCS2 } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

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