Creating a Simple XML Web Service


Before a .NET Compact Framework XML Web service client can be created, there must exist an XML Web Service that the client can consume. In this chapter a simple Web service is created, and a .NET Compact Framework client is created to consume it. This XML Web service returns a famous quote, the name of the person who first spoke or wrote the quote, and the years during which the person lived.

The quotes will be stored in a Microsoft SQL Server database. When a request for a quote is made, the XML Web service will query for a random quote and return that quote to the client. You will need to set up this database before you can run this sample. See the Readme.txt file in the media for this chapter for instructions on setting up the database.

To create the XML Web service, start a new project in Visual Studio.NET. Use the ASP.NET Web Service template. Name the project QuotableQuotesWebService . An XML Web service named Service1 will be created in the Service1.asmx file. Rename this XML Web service to QuoteService and the .aspx source file to QuoteService.aspx .

The XML Web service will expose one web method, GetQuote . This method returns the quote information. The quote information is first pulled from the Microsoft SQL Server database. There is a stored procedure in the QuotableQuotes database named GetQuote that we will use to query the quote information. Microsoft Visual Studio.NET will assist in writing code to interact with this stored procedure. First open the Server Explorer and locate the GetQuote stored procedure in the QuotableQuotes database. Drag the GetQuote stored procedure onto the XML Web service designer. This will create two objects: sqlConnection1 and sqlCommand1 . The sqlConnection1 object is of type SqlConnection and represents the connection to the QuotableQuotes database. The sqlCommand1 object is of type SqlCommand and represents the SQL command that will retrieve the quote information from the stored procedure. Rename the sqlConnection1 and sqlCommand1 to quoteConnection and cmdGetQuote , respectively.

Before implementing GetQuote , there needs to be a helper method to generate random quotes. The cmdGetQuote SqlCommand takes one parameter. This parameter is the unique ID of the quote record in the database. In the database each quote has a unique identifier of type integer . The identifiers sequentially increment by one, with the first quote having the ID of zero. The QuotableQuote XML Web service will return a random quote. To do this, the code must generate a random number between zero and the largest quote identifier in the database. The largest quote identifier must be retrieved from the database. There is a stored procedure named GetLargestQuoteIdentifier in the database to do just this. Locate the GetLargestQuoteID stored procedure, and drag it onto the designer. This will create another SqlCommand object. Rename this object to cmdGetLargestID . Listing 9.1 demonstrates how to retrieve the largest quote ID from the the database. This code should be placed in the QuoteService class.

Listing 9.1
 C# public Int64 LargestID {   get   {     object largestID = cmdGetLargestID.ExecuteScalar();     if(largestID== null  !(largestID is Int64))       return -1;     return (Int64)largestID;   } } VB Public ReadOnly Property LargestID() As Int64   Get     Dim largeID As Object     largeID = Me.cmdGetLargestID.ExecuteScalar()     If (largeID Is Nothing) Or Not (TypeOf largeID Is Int64) Then       Return -1     End If     Return CLng(largeID)   End Get End Property 

The preceding code retrieves that largest quote identifier from the Quotes table. First, the cmdGetLargestID SqlCommand object is used to get the largest quote identifier from the database. Then the value that is retrieved is checked for validity. Negative one ( “1) is returned if the value is invalid.

After retrieving the largest quote identifer, a random quote ID can be generated. This is done with the System.Random class. The System.Random class represents a pseudo-random number generator. The Next method will be used to retrieve a random integer ( Int32 ). The Next method can accept an integer ( Int32 ) that represents the upper bound of the random number to be generated. In this sample the largest quote id will be passed as this parameter.

Tthe GetQuote method will return a custom data structure that contains the quote data. Listing 9.2 contains the Quote class that holds the quote data. The class should be placed in the QuoteService.aspx file inside of the namespace.

Listing 9.2
 C# public class Quote {   public string String;   public string Author;   public string Date; } VB Class Quote     Public Str As String     Public Author As String     Public Data As String End Class 

Now that data structures are out of the way, the GetQuote method must be implemented. The GetQuote Web method needs to complete the following tasks :

  1. Generate a random Quote ID

  2. Get the quote data from the database

  3. Fill the Quote data structure

  4. Return the Quote data structure

The code in Listing 9.3 should replace the commented-out HelloWorld method in the QuoteService.aspx file.

Listing 9.3
 C# [WebMethod] public Quote GetQuote() {   quoteConnection.Open();   try   {     Int64 largestID = LargestID;     if(-1 == largestID)       return null;     Random rand = new Random(DateTime.Now.Millisecond);     Int64 randomQuoteId = rand.Next((int)largestID);     cmdGetQuote.Parameters["@id"] =       new SqlParameter("@id", randomQuoteId);     SqlDataReader reader = cmdGetQuote.ExecuteReader();     if(!reader.Read())       return null;     Quote q = new Quote();     q.String = reader.GetString(0);  // Get Quote String     q.Author = reader.GetString(1);  // Get author's name     q.Date = reader.GetString(2);    // Get the spoken date     return q;   }   finally   {     quoteConnection.Close();   } } VB <WebMethod()> _ Public Function GetQuote() As Quote   Me.quoteConnection.Open()   Try     Dim largeID As Long     largeID = LargestID()     If -1 = largeID Then       Return Nothing     End If     Dim randomQuoteID As Int64     Dim rand As New Random(DateTime.Now.Millisecond)     randomQuoteID = rand.Next(CInt(largeID))     Me.cmdGetQuote.Parameters("@id") = _       New SqlParameter("@id", randomQuoteID)     Dim reader As SqlDataReader     reader = Me.cmdGetQuote.ExecuteReader()     If Not reader.Read() Then       Return Nothing     End If     Dim quote As New Quote     quote.Str = reader.GetString(0)     quote.Author = reader.GetString(1)     quote.Data = reader.GetString(2)     Return quote   Finally     Me.quoteConnection.Close()   End Try End Function 

First the connection to the QuotableQuotes database is opened by calling the Open method on the quoteConnection object. Next a random number between zero and the largest quote identifier is generated by the Next method on the System.Random class. The ID is checked for validity. If the ID is valid, this number is set as the named parameter @id of the cmdGetQuote SqlCommand object. Next the ExecuteReader method of the SqlCommand object is called. This method executes the command against the Microsoft SQL Server database and returns a SqlDataReader object that provides access to the quote data. Then the SqlDataReader fills the Quote data structure. Finally, the Quote data structure is returned to the caller, and the finally block ensures the database connection is closed even in the case of an unexpected exception. Before the classes in the SqlClient namespace can be used, the System.Data.SqlClient namespace must be imported into the QuoteService.aspx code file.

There is one more detail that needs to be handled. By default, a new Web service is put in the http://tempura.org namespace. Microsoft recommends that each XML Web service have a unique XML namespace that identifies it. This allows client applications to distinguish it from other services on the Web. This can be done by applying the WebServiceAttribute attribute to the Web service class. Add the following line of code directly above the QuoteService class:

 
 C# [WebService(Namespace="http://netcfkickstart/QuoteService",             Description="Provides access to famous quotes")] VB <WebService(Namespace:="http://netcfkickstart/QuoteService", _             Description:="Provides access to famous quotes")> _ 

This attribute changes the namespace of the QuoteService as well as adds a brief description of the Web service.

With the WebServiceAttribute attribute applied to the Web service, the QuotableQoutes Web service can be compiled and tested . Press F5 to compile and debug the XML Web service. This brings up the QuoteService discovery Web page. The discovery Web page contains the string description from the WebServiceAttribute attribute. The page contains a link labeled Service Description . This link will display the formal WSDL file for the service. There is also a link with the text GetQuote . Clicking this link will bring up a Web page that allows testing of the GetQuote Web method.

The test page provides several pieces of information. Clicking the Invoke button on the test page will invoke the Web method and display the return data in Internet Explorer. The following XML is an example of the results from the GetQuote test page:

 
 <?xml version="1.0" encoding="utf-8" ?> <Quote xmlns:xsd="http://www.w3.org/2001/XMLSchema"             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"             xmlns="http://netcfkickstart/QuoteService">   <String>    "Once you eliminate the impossible, whatever remains, no matter how    improbable, must be the truth."    </String>    <Author>Sherlock Holmes</Author>           <Date>1859-1930</Date>    </Quote> 

Besides providing the ability to test the Web service, the test page provides three examples of how to format a request to the Web service and sample responses. These examples include formatting for HTTP-POST , HTTP-GET , and SOAP .



Microsoft.NET Compact Framework Kick Start
Microsoft .NET Compact Framework Kick Start
ISBN: 0672325705
EAN: 2147483647
Year: 2003
Pages: 206

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