Recipe 11.3 Creating a Web Service That Returns a Custom Object

     

11.3.1 Problem

You want to create a web service that returns a custom object, because none of the .NET data types meets your needs.

11.3.2 Solution

Create a class that encapsulates the data you need and use it as the return type of a method of your web service.

To demonstrate this solution, we have created the custom class, BookData , shown in Example 11-11 (VB) and Example 11-12 (C#). The class encapsulates information about books stored in a database. A class that uses a web service that returns book information from a database using the custom class is shown in Example 11-13 (VB) and Example 11-14 (C#). Example 11-15 through Example 11-17 show the .aspx file and VB and C# code-behind files for our application that demonstrates how we use the web service.

11.3.3 Discussion

Web services use XML to transfer data, and rely on the common language runtime (CLR) to serialize most data types to XML. If you create an object that contains public properties or variables of the types the CLR can serialize, the CLR will serialize the object for you with no additional coding when it is used as the return type of a web service.

A custom object that is to be returned by a web service must meet two requirements. First, the object must contain only data types that can be serialized (they must implement the ISerializable interface). All of the .NET base data types and the majority of its complex data types can be serialized. The notable exceptions are DataTable , DataRow , and DataView .

Second, the class defining the object must include a public default constructor (one with no parameters). The CLR uses this constructor to serialize the object.

Let's take a look at the code we have written to illustrate this solution. To begin with, we have created the class shown in Example 11-11 (VB) and Example 11-12 (C#), which encapsulates the object that a method of the web service will return. The class consists of the four sections shown in Table 11-1.

Table 11-1. Elements of the class returned by the sample web service

Element

Description

Private attributes

Used to store the object data

Public properties

Used to access the object data

First constructor

Used to create the object and populate it with data for a specific book

Second constructor

Provides the default public constructor required for serialization and provides the ability to create an object with all default values


The class shown in Example 11-13 (VB) and Example 11-14 (C#) implements our web service. To make our example more useful, the getBookList method described in Recipe 11.1 is included in this class. For more on the getBookList web service method, refer to Recipe 11.1.

In our example, the getBookData method creates an instance of the BookData class and uses it as the return type for the method. The ID of the required book and the current HttpContext are passed to provide the constructor the information it needs to create the object and populate it with the requested book data.

 
figs/vbicon.gif
 bookInfo = New BookData(bookID, _ Context) Return (bookInfo) 
figs/csharpicon.gif
 bookInfo = new BookData(bookID, Context); return (bookInfo); 

Our .aspx file shown in Example 11-15 uses a ListBox to display a list of available books and a group of Literal controls to display the Title, ISBN, and other details about the book.

The Page_Load method in our example's code-behind, shown in Example 11-16 (VB) and Example 11-17 (C#), is responsible for populating the ListBox with the list of available books. Our first step is to create an instance of the web service proxy class.

In our example, the web reference was renamed to ExampleBookServices and the class that implements the web service is named CH11BookServicesVB (or CH11BookServicesCS ).


 
figs/vbicon.gif
 bookServices = New ExampleBookServices.CH11BookServicesVB 
figs/csharpicon.gif
 bookServices = new ExampleBookServices.CH11BookServicesCS( ); 

Our next step is to call the getBookList method of the proxy class to get a list of available books.

 
figs/vbicon.gif
 books = bookServices.getBookList(NUMBER_OF_BOOKS) 
figs/csharpicon.gif
 books = bookServices.getBookList(NUMBER_OF_BOOKS); 

After getting the list, the data is bound to the ListBox by setting the DataSource property to the DataSet containing the list of books. The DataTextField is set to the column in the DataSet containing the title of the book to define what will be displayed in the ListBox . The DataValueField is set to the column in the DataSet containing the BookID to uniquely identify the book when an item is selected. Finally, the DataBind method is called to bind the data in the DataSet to the ListBox .

 
figs/vbicon.gif
 lstBooks.DataSource = books lstBooks.DataTextField = "Title" lstBooks.DataValueField = "BookID" lstBooks.DataBind( ) 
figs/csharpicon.gif
 lstBooks.DataSource = books; lstBooks.DataTextField = "Title"; lstBooks.DataValueField = "BookID"; lstBooks.DataBind( ); 

Rather than attempting to handle the case where the user does not select a book in the ListBox , we have simplified our example by selecting the first book in the list and then calling the getBookDetails method (described next).

 
figs/vbicon.gif
 lstBooks.SelectedIndex = 0 getBookDetails( ) 
figs/csharpicon.gif
 lstBooks.SelectedIndex = 0; getBookDetails( ); 

The getBookDetails method is responsible for calling the web service that retrieves the details of the selected book. The getBookData method that is exposed by the web service is responsible for returning a custom object.

First, the method gets the ID of the selected book from the ListBox .

 
figs/vbicon.gif
 bookID = CInt(lstBooks.SelectedItem.Value) 
figs/csharpicon.gif
 bookID = System.Convert.ToInt32(lstBooks.SelectedItem.Value); 

Next, an instance of the web service proxy class is created and the getBookData method is called to get the details of the book from the web service.

 
figs/vbicon.gif
 bookServices = New ExampleBookServices.CH11BookServicesVB bookInfo = bookServices.getBookData(bookID) 
figs/csharpicon.gif
 bookServices = new ExampleBookServices.CH11BookServicesCS( ); bookInfo = bookServices.getBookData(bookID); 

The controls used to display the book details are then initialized with the data in the BookData object returned from the web service.

 
figs/vbicon.gif
 litTitle.Text = bookInfo.title litIsbn.Text = bookInfo.Isbn litDescription.Text = bookInfo.description litPublisher.Text = bookInfo.publisher litListPrice.Text = bookInfo.listPrice.ToString("0.00") litDate.Text = bookInfo.publishDate.ToShortDateString( ) 
figs/csharpicon.gif
 litTitle.Text = bookInfo.title; litIsbn.Text = bookInfo.Isbn; litDescription.Text = bookInfo.description; litPublisher.Text = bookInfo.publisher; litListPrice.Text = bookInfo.listPrice.ToString("0.00"); litDate.Text = bookInfo.publishDate.ToShortDateString( ); 

One of the primary benefits of encapsulating data as we have in this example is the improvement in the performance of the web service. By returning the custom BookData object from our web service, all of the data is retrieved in a single call. If each piece of data for the book is obtained using separate calls, the application's performance will be significantly reduced. When you use a web service to retrieve data, it is usually best to return the largest possible block of data for each call. This reduces the significant overhead of serializing the data to XML and wrapping it with SOAP and HTTP protocol wrappers.

.NET Web Service Idiosyncrasies

Web services that are produced and consumed by .NET applications can use any of the data types of the Common Language Runtime (CLR) that implement the ISerializable interface. If your web services need to be consumed by other technologies, such as Java, it will be necessary to limit the data types to simple types, such as integer, string, etc. In addition, .NET web services use Document Literal encoding by default, while many other technologies use RPC encoding. These factors must be considered when developing web services that are produced and consumed by different technologies.


Web Services Return Data Only

Web services let you pass simple or complex data between applications; however, they cannot pass behavior. If you create a typical class that provides methods to act upon the data in the instantiated object and use it as the return type from a web service method, you will find the methods to act upon the data are not available when the object is returned. While the object created by the web service and the object created by the application consuming the web service have the same name , they are not created from the same class. The BookData proxy class (VB version) created for our example is shown here. You will notice that it does not resemble the BookData class shown in Example 11-11. Essentially, it is just a structure containing the data exposed by the class returned by the web service.

 <System.Xml.Serialization.XmlTypeAttribute([Namespace]:="http:// www.dominiondigital.com")> _ Public Class BookData '<remarks/> Public title As String '<remarks/> Public Isbn As String '<remarks/> Public description As String '<remarks/> Public publisher As String '<remarks/> Public listPrice As Single '<remarks/> Public publishDate As Date '<remarks/> Public bookID As Integer End Class 


11.3.4 See Also

Recipe 11.1

Example 11-11. Custom class (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: BookData.vb ' ' Description: This class provides the data class used to encapsulate ' book data returned from a web service ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System Imports System.Configuration Imports System.Data Imports System.Data.OleDb Imports System.Web Namespace VBWebServices Public Class BookData 'private attributes Private mBookID As Integer Private mTitle As String Private mIsbn As String Private mDescription As String Private mPublisher As String Private mListPrice As Single Private mPublishDate As DateTime '************************************************************************* ' ' ROUTINE: bookID ' ' DESCRIPTION: This property provides the ability to get/set the ' book ID '------------------------------------------------------------------------- Public Property bookID( ) As Integer Get Return (mBookID) End Get Set(ByVal Value As Integer) mBookID = Value End Set End Property 'bookID '************************************************************************* ' ' ROUTINE: title ' ' DESCRIPTION: This property provides the ability to get/set the ' title '------------------------------------------------------------------------- Public Property title( ) As String Get Return (mTitle) End Get Set(ByVal Value As String) mTitle = Value End Set End Property 'title '************************************************************************* ' ' ROUTINE: Isbn ' ' DESCRIPTION: This property provides the ability to get/set the ' ISBN '------------------------------------------------------------------------- Public Property Isbn( ) As String Get Return (mIsbn) End Get Set(ByVal Value As String) mIsbn = Value End Set End Property 'Isbn '************************************************************************* ' ' ROUTINE: description ' ' DESCRIPTION: This property provides the ability to get/set the ' description '------------------------------------------------------------------------- Public Property description( ) As String Get Return (mDescription) End Get Set(ByVal Value As String) mDescription = Value End Set End Property 'description '************************************************************************* ' ' ROUTINE: publisher ' ' DESCRIPTION: This property provides the ability to get/set the ' publisher '------------------------------------------------------------------------- Public Property publisher( ) As String Get Return (mPublisher) End Get Set(ByVal Value As String) mPublisher = Value End Set End Property 'publisher '************************************************************************* ' ' ROUTINE: listPrice ' ' DESCRIPTION: This property provides the ability to get/set the ' listPrice '------------------------------------------------------------------------- Public Property listPrice( ) As Single Get Return (mListPrice) End Get Set(ByVal Value As Single) mListPrice = Value End Set End Property 'listPrice '************************************************************************* ' ' ROUTINE: publishDate ' ' DESCRIPTION: This property provides the ability to get/set the ' publishDate '------------------------------------------------------------------------- Public Property publishDate( ) As DateTime Get Return (mPublishDate) End Get Set(ByVal Value As Date) mPublishDate = Value End Set End Property 'publishDate '************************************************************************* ' ' ROUTINE: New ' ' DESCRIPTION: This constructor creates the object and populates it ' with data for the passed book ID. '------------------------------------------------------------------------- Public Sub New(ByVal ID As Integer, _ ByVal context As HttpContext) Dim dbConn As OleDbConnection Dim da As OleDbDataAdapter Dim dTable As DataTable Dim dRow As DataRow Dim strConnection As String Dim strSQL As String Try 'get the connection string from web.config and open a connection 'to the database strConnection = _ ConfigurationSettings.AppSettings("dbConnectionString") dbConn = New OleDbConnection(strConnection) dbConn. Open ( ) 'build the query string used to get the data from the database strSQL = "SELECT BookID, Title, ISBN, Description, Publisher, " & _ "ListPrice, PublishDate " & _ "FROM Book " & _ "WHERE BookID=" & ID.ToString( ) 'create a new data table and fill it with the book data dTable = New DataTable da = New OleDbDataAdapter(strSQL, dbConn) da.Fill(dTable) 'populate object with the book data read from the database dRow = dTable.Rows(0) bookID = CInt(dRow.Item("BookID")) title = CStr(dRow.Item("Title")) Isbn = CStr(dRow.Item("ISBN")) description = CStr(dRow.Item("Description")) publisher = CStr(dRow.Item("Publisher")) listPrice = CSng(dRow.Item("ListPrice")) publishDate = CDate(dRow.Item("PublishDate")) Finally 'clean up If (Not IsNothing(dbConn)) Then dbConn.Close( ) End If End Try End Sub 'New '************************************************************************* ' ' ROUTINE: New ' ' DESCRIPTION: This constructor creates the object will default values '------------------------------------------------------------------------- Public Sub New( ) bookID = -1 title = "" Isbn = "" description = "" publisher = "" listPrice = 0 publishDate = DateTime.MinValue End Sub 'New End Class 'BookData End Namespace 

Example 11-12. Custom class (.cs)
 //---------------------------------------------------------------------------- // // Module Name: BookData.cs // // Description: This class provides the data class used to encapsulate // book data returned from a web service // //**************************************************************************** using System; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Web; namespace CSWebServices { public class BookData { // private attributes private int mBookID; private string mTitle; private string mIsbn; private string mDescription; private string mPublisher; private Decimal mListPrice; private DateTime mPublishDate; //************************************************************************ // // ROUTINE: bookID // // DESCRIPTION: This property provides the ability to get/set the // book ID //------------------------------------------------------------------------ public int bookID { get { return(mBookID); } set { mBookID = value; } } // bookID //************************************************************************ // // ROUTINE: title // // DESCRIPTION: This property provides the ability to get/set the // title //------------------------------------------------------------------------ public string title { get { return(mTitle); } set { mTitle = value; } } // title //************************************************************************ // // ROUTINE: Isbn // // DESCRIPTION: This property provides the ability to get/set the // ISBN //------------------------------------------------------------------------ public string Isbn { get { return(mIsbn); } set { mIsbn = value; } } // Isbn //************************************************************************ // // ROUTINE: description // // DESCRIPTION: This property provides the ability to get/set the // description //------------------------------------------------------------------------ public string description { get { return(mDescription); } set { mDescription = value; } } // description //************************************************************************ // // ROUTINE: publisher // // DESCRIPTION: This property provides the ability to get/set the // publisher //------------------------------------------------------------------------ public string publisher { get { return(mPublisher); } set { mPublisher = value; } } // publisher //************************************************************************ // // ROUTINE: listPrice // // DESCRIPTION: This property provides the ability to get/set the // listPrice //------------------------------------------------------------------------ public Decimal listPrice { get { return(mListPrice); } set { mListPrice = value; } } // listPrice //************************************************************************ // // ROUTINE: publishDate // // DESCRIPTION: This property provides the ability to get/set the // publishDate //------------------------------------------------------------------------ public DateTime publishDate { get { return(mPublishDate); } set { mPublishDate = value; } } // publishDate //************************************************************************ // // ROUTINE: BookData // // DESCRIPTION: This constructor creates the object and populates it // with data for the passed book ID. //------------------------------------------------------------------------ public BookData(int ID, HttpContext context) { OleDbConnection dbConn = null; OleDbDataAdapter da = null; DataTable dTable = null; DataRow dRow = null; string strConnection = null; string strSQL = null; try { // get the connection string from web.config and open a connection // to the database strConnection = ConfigurationSettings.AppSettings["dbConnectionString"]; dbConn = new OleDbConnection(strConnection); dbConn.Open( ); //build the query string used to get the data from the database strSQL = "SELECT BookID, Title, ISBN, Description, Publisher, " + "ListPrice, PublishDate " + "FROM Book " + "WHERE BookID=" + ID.ToString( ); // create a new data table and fill it with the book data dTable = new DataTable( ); da = new OleDbDataAdapter(strSQL, dbConn); da.Fill(dTable); // populate object with the book data read from the database dRow = dTable.Rows[0]; bookID = (int)(dRow["BookID"]); title = (string)(dRow["Title"]); Isbn = (string)(dRow["ISBN"]); description = (string)(dRow["Description"]); publisher = (string)(dRow["Publisher"]); listPrice = (Decimal)(dRow["ListPrice"]); publishDate = (DateTime)(dRow["PublishDate"]); } finally { // cleanup if (dbConn != null) { dbConn.Close( ); } } // finally } //************************************************************************ // // ROUTINE: BookData // // DESCRIPTION: This constructor creates the object will default values //------------------------------------------------------------------------ public BookData( ) { bookID = -1; title = ""; Isbn = ""; description = ""; publisher = ""; listPrice = 0; publishDate = DateTime.MinValue; } } // BookData } // CSWebServices 

Example 11-13. Web service returning a custom object (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH11BookServicesVB.asmx.vb ' ' Description: This class provides the code-behind for ' CH11BookServicesVB.asmx. It provides several methods for ' accessing book information. ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System Imports System.Configuration Imports System.Data Imports System.Data.OleDb Imports System.Web.Services Namespace VBWebServices <WebService(Namespace:="http://www.dominiondigital.com/")> _ Public Class CH11BookServicesVB Inherits System.Web.Services.WebService '************************************************************************* ' ' ROUTINE: getBooklist ' ' DESCRIPTION: This routine gets the list of books from the database. '------------------------------------------------------------------------- <WebMethod( )> _ Function getBookList(ByVal numberOfBooks As Integer) As DataSet Dim dbConn As OleDbConnection Dim da As OleDbDataAdapter Dim dSet As DataSet Dim strConnection As String Dim strSQL As String Try 'get the connection string from web.config and open a connection 'to the database strConnection = _ ConfigurationSettings.AppSettings("dbConnectionString") dbConn = New OleDbConnection(strConnection) dbConn.Open( ) 'build the query string used to get the data from the database strSQL = "SELECT Top " & numberOfBooks.ToString( ) & " " & _ "BookID, 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 '************************************************************************* ' ' ROUTINE: getBookData ' ' DESCRIPTION: This routine gets the data for the passed book '-------------------------------------------------------------------------  <WebMethod( )> _   Function getBookData(ByVal bookID As Integer) As BookData   Dim bookInfo As BookData   'create a new BookData object containing the requested data   bookInfo = New BookData(bookID, _   Context)   Return (bookInfo)   End Function ' getBookData  End Class 'CH11BookServicesVB End Namespace 

Example 11-14. Web service returning a custom object (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH11BookServicesCS.aspx.cs // // Description: This module provides the code behind for the // CH11BookServicesCS.aspx page // //**************************************************************************** using System; using System.Configuration; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Web.Services; namespace CSWebServices { [WebService(Namespace="http://www.dominiondigital.com/")] public class CH11BookServicesCS : System.Web.Services.WebService { //************************************************************************ // // ROUTINE: getBookList // // DESCRIPTION: This routine gets the list of books from the database. //------------------------------------------------------------------------ [WebMethod] public DataSet getBookList(int numberOfBooks) { OleDbConnection dbConn = null; OleDbDataAdapter da = null; DataSet dSet = null; String strConnection = null; String strSQL = null; try { // get the connection string from web.config and open a connection // to the database strConnection = ConfigurationSettings.AppSettings["dbConnectionString"]; dbConn = new OleDbConnection(strConnection); dbConn.Open( ); //build the query string used to get the data from the database strSQL = "SELECT Top " + numberOfBooks.ToString( ) + " " + "BookID, 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); } // try finally { // cleanup if (dbConn != null) { dbConn.Close( ); } } // finally } // getBookList //************************************************************************ // // ROUTINE: getBookData // // DESCRIPTION: This routine gets the data for the passed book //------------------------------------------------------------------------  [WebMethod] public BookData getBookData(int bookID)   {   BookData bookInfo = null;   // create a new BookData object containing the requested data   bookInfo = new BookData(bookID,   Context);   return (bookInfo);   } // getBookData  } // CH11BookServicesCS } 

Example 11-15. Using the web service returning a custom object (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH11CustomObjectWithWebServiceVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH11CustomObjectWithWebServiceVB"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Web Service Returning A Custom Object</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmWebService" method="post" runat ="server"> <table width="100%" cellpadding ="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Returning a Custom Object From a Web Service (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="MenuItem"> Available Books<br /><br />  <asp:ListBox ID="lstBooks" Runat="server" AutoPostBack="True" />  </td> </tr> <tr> <td> <br /> <table width="60%" align="center" border="1" bordercolor="#000080" cellpadding="5" cellspacing="0" class="MenuItem"> <tr> <td width="25%" align="right">Title: </td> <td width="75%">  <asp:Literal ID="litTitle" Runat="server" /></td>  </tr> <tr> <td width="25%" align="right">ISBN: </td> <td width="75%">  <asp:Literal ID="litIsbn" Runat="server" /></td>  </tr> <tr> <td width="25%" align="right">Description: </td> <td width="75%">  <asp:Literal ID="litDescription" Runat="server" /></td>  </tr> <tr> <td width="25%" align="right">Publisher: </td> <td width="75%">  <asp:Literal ID="litPublisher" Runat="server" /></td>  </tr> <tr> <td width="25%" align="right">List Price: </td> <td width="75%">  <asp:Literal ID="litListPrice" Runat="server" /></td>  </tr> <tr> <td width="25%" align="right">Date: </td> <td width="75%">  <asp:Literal ID="litDate" Runat="server" /></td>  </tr> </table> </td> </tr> </table> </form> </body> </html> 

Example 11-16. Using the web service returning a custom object code-behind (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH11CustomObjectWithWebServiceVB.aspx.vb ' ' Description: This module provides the code behind for the ' CH11CustomObjectWithWebServiceVB.aspx page ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System Imports System.Data Namespace ASPNetCookbook.VBExamples Public Class CH11CustomObjectWithWebServiceVB Inherits System.Web.UI.Page 'controls on the form Protected WithEvents lstBooks As System.Web.UI.WebControls.ListBox Protected btnDetails As System.Web.UI.WebControls.ImageButton Protected litTitle As System.Web.UI.WebControls.Literal Protected litIsbn As System.Web.UI.WebControls.Literal Protected litDescription As System.Web.UI.WebControls.Literal Protected litPublisher As System.Web.UI.WebControls.Literal Protected litListPrice As System.Web.UI.WebControls.Literal Protected litDate As System.Web.UI.WebControls.Literal '************************************************************************* ' ' ROUTINE: Page_Load ' ' DESCRIPTION: This routine provides the event handler for the page load ' event. It is responsible for initializing the controls ' on the page. '------------------------------------------------------------------------- Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Const NUMBER_OF_BOOKS As Integer = 20 Dim bookServices As ExampleBookServices.CH11BookServicesVB Dim books As DataSet If (Not Page.IsPostBack) Then 'create an instance of the web service proxy class bookServices = New ExampleBookServices.CH11BookServicesVB 'get the books from the service books = bookServices.getBookList(NUMBER_OF_BOOKS) 'bind the book list to the listbox on the form lstBooks.DataSource = books lstBooks.DataTextField = "Title" lstBooks.DataValueField = "BookID" lstBooks.DataBind( ) 'select the first item in the list and get the details lstBooks.SelectedIndex = 0 getBookDetails( ) End If End Sub 'Page_Load '************************************************************************* ' ' ROUTINE: lstBooks_SelectedIndexChanged ' ' DESCRIPTION: This routine provides the event handler for the book ' listbox selected index changed event. It is responsible ' for getting the book data for the selected book '------------------------------------------------------------------------- Private Sub lstBooks_SelectedIndexChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles lstBooks.SelectedIndexChanged 'get the data for the selected book getBookDetails( ) End Sub 'lstBooks_SelectedIndexChanged '************************************************************************* ' ' ROUTINE: getBookDetails ' ' DESCRIPTION: This routine gets the details for the currently ' selected book and initializes the controls on the ' with the data. '-------------------------------------------------------------------------  Private Sub getBookDetails( )   Dim bookServices As ExampleBookServices.CH11BookServicesVB   Dim bookInfo As ExampleBookServices.BookData   Dim bookID As Integer   'get the currently selected book   bookID = CInt(lstBooks.SelectedItem.Value)   'create an instance of the web service proxy class   'and get the book data   bookServices = New ExampleBookServices.CH11BookServicesVB   bookInfo = bookServices.getBookData(bookID)   'set the controls on the form to display the book data   litTitle.Text = bookInfo.title   litIsbn.Text = bookInfo.Isbn   litDescription.Text = bookInfo.description   litPublisher.Text = bookInfo.publisher   litListPrice.Text = bookInfo.listPrice.ToString("0.00")   litDate.Text = bookInfo.publishDate.ToShortDateString( )   End Sub 'getBookDetails  End Class 'CH11CustomObjectWithWebServiceVB End Namespace 

Example 11-17. Using the web service returning a custom object code-behind (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH11CustomObjectWithWebServiceCS.aspx.cs // // Description: This module provides the code behind for the // CH11CustomObjectWithWebServiceCS.aspx page // //**************************************************************************** using System; using System.Data; namespace ASPNetCookbook.CSExamples { public class CH11CustomObjectWithWebServiceCS : System.Web.UI.Page { // controls on the form protected System.Web.UI.WebControls.ListBox lstBooks; protected System.Web.UI.WebControls.ImageButton btnDetails; protected System.Web.UI.WebControls.Literal litTitle; protected System.Web.UI.WebControls.Literal litIsbn; protected System.Web.UI.WebControls.Literal litDescription; protected System.Web.UI.WebControls.Literal litPublisher; protected System.Web.UI.WebControls.Literal litListPrice; protected System.Web.UI.WebControls.Literal litDate; //************************************************************************ // // ROUTINE: Page_Load // // DESCRIPTION: This routine provides the event handler for the page // load event. It is responsible for initializing the // controls on the page. //------------------------------------------------------------------------ private void Page_Load(object sender, System.EventArgs e) { const int NUMBER_OF_BOOKS = 20; ExampleBookServices.CH11BookServicesCS bookServices = null; DataSet books = null; // wire the selected index changed event this.lstBooks.SelectedIndexChanged += new System.EventHandler(this.lstBooks_SelectedIndexChanged); if (!Page.IsPostBack) { // create an instance of the web service proxy class bookServices = new ExampleBookServices.CH11BookServicesCS( ); // get the books from the service books = bookServices.getBookList(NUMBER_OF_BOOKS); // bind the book list to the listbox on the form lstBooks.DataSource = books; lstBooks.DataTextField = "Title"; lstBooks.DataValueField = "BookID"; lstBooks.DataBind( ); // select the first item in the list and get the details lstBooks.SelectedIndex = 0; getBookDetails( ); } } // Page_Load //************************************************************************ // // ROUTINE: lstBooks_SelectedIndexChanged // // DESCRIPTION: This routine provides the event handler for the book // listbox selected index changed event. It is // responsible for getting the book data for the // selected book //------------------------------------------------------------------------ private void lstBooks_SelectedIndexChanged(Object sender, System.EventArgs e) { // get the data for the selected book getBookDetails( ); } // lstBooks_SelectedIndexChanged //************************************************************************ // // ROUTINE: getBookDetails // // DESCRIPTION: This routine gets the details for the currently // selected book and initializes the controls on the // with the data. //------------------------------------------------------------------------  private void getBookDetails( )   {   ExampleBookServices.CH11BookServicesCS bookServices = null;   ExampleBookServices.BookData bookInfo = null;   int bookID;     // get the currently selected book   bookID = System.Convert.ToInt32(lstBooks.SelectedItem.Value);   // create an instance of the web service proxy class   // and get the book data   bookServices = new ExampleBookServices.CH11BookServicesCS( );   bookInfo = bookServices.getBookData(bookID);   // set the controls on the form to display the book data   litTitle.Text = bookInfo.title;   litIsbn.Text = bookInfo.Isbn;   litDescription.Text = bookInfo.description;   litPublisher.Text = bookInfo.publisher;   litListPrice.Text = bookInfo.listPrice.ToString("0.00");   litDate.Text = bookInfo.publishDate.ToShortDateString( );   } // getBookDetails  } // CH11CustomObjectWithWebServiceCS } 



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

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