Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

530Chapter 12 • Creating an ADO.NET Shopping Cart

5.Return string indicating success or failure of the operation.

updateItem (string ISBN, string author, double price, string

title, string description, string imagePath, int CAT_ID) Updates a book item’s information.

1.Call init().

2.Create Command object accessing the AdminUpdateBook proc.

3.Create the Parameter objects and assign their values.

4.Execute the procedure. Call ExecuteQuery( commandObj ).

5.Return string indicating success or failure of the operation.

addCat (string CAT_Name) Adds a category name to the database.

1.Call init().

2.Create Command object accessing the AdminAddCat proc.

3.Create the Parameter object and assign its value.

4.Execute the procedure. Call ExecuteQuery(commandObj).

5.Return string indicating success or failure of the operation.

updateCat (int CAT_ID, string CAT_Name) Updates category details.

1.Call init().

2.Create Command object accessing the AdminUpdateCat proc.

3.Create the Parameter objects and assign their values.

4.Execute the procedure. Call ExecuteQuery(commandObj).

5.Return string indicating success or failure of the operation.

removeCat (int CAT_ID) Removes a category from the database.

1.Call init().

2.Create Command object accessing the AdminUpdateCat proc.

3.Create the Parameter object and assign its value.

4.Execute the procedure. Call ExecuteQuery(commandObj).

5.Return string indicating success or failure of the operation.

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

531

NOTE

This application contains several different Web Services. The code for these Web Services can be found on the CD. (See adminCustomer.asmx.cs, sellerAdmin.asmx.cs, getBooks.asmx.cs, getCategories.asmx.cs, getCustomer.asmx.cs, loginCustomer.asmx.cs, orderBooks.asmx.cs,

and sellerAdmin.asmx.cs.)

Now that we know the Web Service and its methods are working correctly, the next step will be to create our UI for the Web application and generate proxy classes for it to retrieve data from our Web Services. In the next section, we will see how VS.NET works with WSDL and Universal Description, Discovery, and Integration (UDDI) to enable our ASP.NET Web Application to connect to and retrieve data from our booksource Web Service project.

Using WSDL Web References

We will use WSDL and disco in our Web application project to connect to and add a reference to our Web Services Application (bookSource) and its individual Web Services and their Web methods.To learn more about WSDL, disco, and Web Services, please see the discussion of this topic in Chapter 10.

Let’s create a new C# Web application, named “bookSourceUI.”The first thing we want to do is create a reference to our Web Services so that we can easily access the methods in our code.

1.In the Solution Explorer pane, right-click Web References.

2.Select Add Web Reference. A new dialog will appear.

3.Select the last UDDI option, which is your local machine.VS.NET will

check your server for all Web Services. It will then present you with a list of services you can view or select to add a reference to. See Figure 12.18.

4.Select the service group you would like to add a reference to. Look for your Web Service project name (http://localhost/bookSource.vsdisco).

5.The Services available will be displayed. See Figure 12.19.

www.syngress.com

532 Chapter 12 • Creating an ADO.NET Shopping Cart

Figure 12.18 UDDI Server Discovery Dialog

Figure 12.19 Services Available

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

533

6.You can view the Simple Object Access Protocol (SOAP) contracts and documentation for each Service method by clicking on the link. Be sure to add the reference from this level in the menu.To add this Web Service and all its methods, click Add Reference.VS.NET will create proxy classes for each Service method so that the method can be accessed just like a local class method. See Figure 12.20.

Figure 12.20 Proxy Classes Added to Solution Explorer in VSNET UI

Building the Site

Now that the backend database interfaces and Web Services have been completed, we will turn our focus to the middle tier data classes and controls that act as a bridge between the backend and the Web UI. Our site structure will look something like that depicted in Figure 12.21.

Site Administration

In this section, we will develop the code that allows us to tie our site administration interface to our Web Services (see Figure 12.22).While creating the pages needed, we will cover creating the Administration login, creating the Administration page, and an addBook page for the administrator.

www.syngress.com

534 Chapter 12 • Creating an ADO.NET Shopping Cart

Figure 12.21 BookShop Site Overview

 

 

start.aspx

 

 

 

start.aspx.cs

 

 

 

Common file used

 

 

in all UI pages.

 

 

Contains the

 

 

navigation bar.

 

 

header.htm

 

loginCustomer.aspx

 

adminLogin.aspx

 

loginCustomer

 

adminLogin

 

.aspx.cs

 

.aspx.cs

updateCustomerInfo.

newCustomer.aspx

adminPage.aspx

addBook.aspx

aspx

 

 

 

updateCustomerInfo.

newCustomer

adminPage

addBook

aspx.cs

.aspx.cs

.aspx.cs

.aspx.cs

Customer Admin Pages

 

Site Admin Pages

Figure 12.22 Site Administration Page Group Overview

 

adminLogin.aspx

 

adminLogin

 

.aspx.cs

adminPage.aspx

addBook.aspx

adminPage

addBook

.aspx.cs

.aspx.cs

Site Admin Pages

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

535

Creating the Administration Login (adminLogin.aspx)

This is a fairly simple page that uses the asp:RequiredFieldValidator server control. There are several server controls that enable HTML form validation:

RequiredFieldValidator

CompareValidator

RangeValidator

RegularExpressionValidator

CustomValidator

ValidationSummary

All of these controls work in a similar fashion. In this example page, we use RequiredFieldValidator in a code behind page to show how to use a server control to validate user data in HTML forms.

1.In the Web application bookSourceUI, create a new aspx page, and name it adminLogin.aspx.

2.In Design view, drag and drop a RequiredFieldValidator.

3.Be sure not to position this element in Design view; in the aspx page, remove the style attribute from the element and use HTML layout techniques to position it. (See the sidebar in this section on ASP.NET and Netscape.)

Let’s look at the code from the .aspx page:

<tr>

<td><FONT face="Verdana" size="2">User:</FONT> </td> <td style="WIDTH: 127px">

<asp:textbox id="txtUser" runat="server" Width="106px" Height="24px">

</asp:textbox>

</td><td>

<asp:requiredfieldvalidator id="passUser" runat="server" ErrorMessage="You must supply a user name" ControlToValidate="txtUser" Width="121px" Height="57px">

www.syngress.com

536 Chapter 12 • Creating an ADO.NET Shopping Cart

</asp:requiredfieldvalidator>

</td>

</tr>

Lets look at a code snippet from the code-behind file (the aspx.cs page). When we drag the RequiredFieldValidator onto the page,VS.NET will add the following:

protected System.Web.UI.WebControls.RequiredFieldValidator passUValid;

And that’s all there is to it.When the page is run, a reference is made to a client-side JavaScript file that includes crossbrowser code to ensure that this field contains a value before allowing a “submit.” If the user tries to submit without filling in the text box, the error message “You must supply a user name” will appear in the table cell to the right of the text box (it actually appears wherever the asp:requiredfieldvalidator tag is placed in the HTML, in this case an adjacent table cell). Next, we will look at the admin page itself.

Debugging…

ASP.NET Server Controls Do Not

Display Correctly in Netscape 4.x

A lot has happened over the last few years with Netscape and the open source Mozilla project. While the newer versions of Mozilla version .094 and later should handle this fine, there is still a significant Netscape 4.x user base. When we develop Web front-ends for our clients, we strive to ensure at least Netscape 4.72 will display and function correctly.

What’s the issue? It seems that most of the examples showing you how to use server controls have you drag and drop the control to where you want it on the screen. In HTML, this creates span tags with inline style attributes containing “absolute positioning.” Those of us that have dealt with cross-browser Dynamic HTML (DHTML) issues know that this can cause problems in Netscape. The solution: Use “FlowLayout” and good old-fashioned HTML elements and tricks for positioning. To do this, simply right-click a page in either “Design” or “HTML” view and switch the pageLayout property to FlowLayout.

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

537

Creating the Administrator Page (adminPage.aspx)

The purpose of this page is to allow the site administrator the ability to remove and update book item information. In the following sections, we’ll look specifically at retrieving the data, displaying the data, adding new books to the database, deleting books, and updating book details.

Retrieving the Data: Creating the getBooks.AllBooks Web Method

To retrieve the list of books stored in the database, we will need to access the “GetAllBooks” stored procedure (MSSQL) or parameterized query (MS Access). We will do this by creating the allBooks method of the getBooks Web Service.This method will take no parameters, and will return a DataSet containing all Book data as well as the table structure of the Database table that the data originated from.The Web method getBooks.AllBooks can be found on the CD that accompanies this book (see getBooks.asmx.cs).

1.To create this method, we must first create a new Web Service named “getBooks”. (See the section on Web Services earlier in this chapter.)

2.Inside the code-behind page of getBooks (getbooks.asmx.cs), we need to create the method allBooks. AllBooks should return a DataSet:

public DataSet AllBooks()

3. Set the connection string:

string source = "Provider=SQLOLEDB.1;Persist Security Info=False …

4. Create the Connection object:

OleDbConnection conn = new OleDbConnection ( source ) ;

5. Create the Command object accessing the “GetAllBooks” proc:

OleDbCommand cmd = new OleDbCommand ( "GetAllBooks" , conn ) ;

cmd.CommandType = CommandType.StoredProcedure;

6. Create a DataAdapter object for the Command object:

OleDbDataAdapter da = new OleDbDataAdapter (cmd) ;

www.syngress.com

538 Chapter 12 • Creating an ADO.NET Shopping Cart

7.Create a new DataSet and use the DataAdapter to fill it from the results of executing the stored procedure:

DataSet ds = new DataSet ( ) ;

da.Fill ( ds , "Books" ) ;

8. Close the connection and return the DataSet:

conn.Close();

return ds;

Here is the method in its entirety:

[WebMethod(Description="This will return all books in an XML String", EnableSession=false)]

public DataSet AllBooks()

{

string source = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=[userID];password = [password]; Initial Catalog=[database name];

Data Source=[server name];Use Procedure for Prepare=1;

Auto Translate=True;Packet Size=4096;

OleDbConnection conn = new OleDbConnection( source ); conn.Open ( ) ;

OleDbCommand cmd = new OleDbCommand ("GetAllBooks" , conn); cmd.CommandType = CommandType.StoredProcedure; OleDbDataAdapter da = new OleDbDataAdapter (cmd) ;

DataSet ds = new DataSet ( ) ; da.Fill ( ds , "Books" ) ; conn.Close();

return ds;

}

The data returned contains an embedded xsd schema describing the Database table “Books”.

<?xml version="1.0" encoding="utf-8"?>

<DataSet xmlns="http://tempuri.org/">

<xsd:schema id="NewDataSet" targetNamespace=""

xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata=

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

539

"urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="NewDataSet" msdata:IsDataSet="true">

<xsd:complexType>

<xsd:choice maxOccurs="unbounded"> <xsd:element name="Books">

<xsd:complexType>

<xsd:sequence>

<xsd:element name="isbn" type="xsd:string" minOccurs="0" /> <xsd:element name="name" type="xsd:string" minOccurs="0" /> <xsd:element name="id" type="xsd:int" minOccurs="0" /> <xsd:element name="imgSrc" type="xsd:string" minOccurs="0" /> <xsd:element name="author" type="xsd:string" minOccurs="0" /> <xsd:element name="price" type="xsd:decimal" minOccurs="0" /> <xsd:element name="title" type="xsd:string" minOccurs="0" /> <xsd:element name="description" type="xsd:string"

minOccurs="0" /> </xsd:sequence>

</xsd:complexType>

</xsd:element>

</xsd:choice>

</xsd:complexType>

</xsd:element>

</xsd:schema>

The next section is the diffgram node, which contains all the table records:

<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">

<NewDataSet xmlns="">

<Books diffgr:id="Books1" msdata:rowOrder="0"> <isbn>0072121599</isbn>

<name>cisco</name>

<id>2</id>

<imgSrc>ccda.gif</imgSrc> <author>Syngress Media Inc</author> <price>49.99</price>

www.syngress.com