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

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

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

540 Chapter 12 • Creating an ADO.NET Shopping Cart

<title>Ccda Cisco Certified Design Associate Study Guide</title> <description>Written for professionals intending on taking the CCDA

test, this special guide covers all the basics of the test and includes hundreds of test questions on the enclosed CD.

</description>

</Books>

<Books diffgr:id="Books2" msdata:rowOrder="1"> <isbn>0072126671</isbn>

<name>cisco</name>

<id>2</id>

<imgSrc>ccna.gif</imgSrc>

<author>Cisco Certified Internetwork Expert Prog</author> <price>49.99</price>

<title>CCNA Cisco Certified Network Associate Study Guide</title> <description>Cisco certification courses are among the fastest-

growing courses in the training industry, and our guides are designed to help readers thoroughly prepare for the exams.

</description>

</Books>.

.

.

This XML file is interpreted by ASP.NET as a DataSet object and can be easily loaded into any variable of type DataSet.The DataGrid control is designed to be DataBinded to a DataSet object.This makes it easy to “data bind” to a Web Service method that returns a DataSet. Data Binding a DataSet to the DataGrid is almost the same as loading the DataSet into the DataGrid.The DataGrid is then able to iterate through and perform operations on the DataSet as if it were an Access Form connected to an Access database.The DataSet in actuality is an inmemory XML representation of the database including the Books table.

Displaying the Data: Binding a DataGrid to the DataSet

The DataGrid is actually bound to the DataTable Books which is a table within the DataSet returned by getBooks.AllBooks.We create a DataView of the Books table so that we can sort the data.This DataView is then bound to the DataGrid.

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

541

In the following code, changeBooks is the name of our DataGrid object:

Dt = Books.AllBooks().Tables["Books"];

myView = new DataView(Dt);

myView.Sort = "isbn";

changeBooks.DataSource = myView;

changeBooks.DataBind();

Adding New Books to the Database:

Creating the allBooks.addItem Web Method

The creation of this method was shown as an example earlier in the chapter, under the section “Web Services.”

Deleting Books: Deleting from the DataGrid and the Database

Using the DataGrid event changeBooks_DeleteCommand, fired when a user clicks the Delete button in the DataGrid UI, we will select the row in the DataGrid to remove by using the RowFilter property.The following code selects the individual book by performing a filter on ISBN. It is analogous to the SQL statement:

Select * from Books where isbn = "@isbn"

The equivalent code for the DataView is:

myView.RowFilter = "isbn='"+upISBN+"'";

This will return an array or collection of items. Since ISBN is our primary key in the Books table, we know that this filter will return only one item.We delete this row from the DataView by simply calling the Delete method:

myView.Delete(0);

Next, we reset the filter so we can re-access the entire Books table:

myView.RowFilter = "";

Now we need to resync the DataGrid with the in-memory Books Table View so that the DataGrid UI reflects the change:

changeBooks.DataSource = myView; changeBooks.DataBind();

www.syngress.com

542 Chapter 12 • Creating an ADO.NET Shopping Cart

Next, we need to update the database to sync it with the DataGrid.This is accomplished by calling the Web method and passing it the ISBN of the book to delete:

removeBook.removeItem(upISBN);

Updating Book Details: Updating

the DataGrid and the Database

Using the DataGrid event changeBooks_UpdateCommand, fired when a user clicks the Update button in the DataGrid UI, we will select the row in the DataGrid to update by using the RowFilter property.

1.Select the row to update by using the RowFilter property of the DataView (see the example in the preceding section).

2.Create a new DataRow Item and populate it with the changes (new Data). Store updated column values in local variables:

string upISBN = e.Item.Cells[2].Text;

string upAuthor = ((TextBox)e.Item.Cells[3].Controls[0]).Text; double upPrice = double.Parse(((TextBox)e.Item.Cells[4].Controls[0]).Text); string upTitle = ((TextBox)e.Item.Cells[5].Controls[0]).Text; string upDescription = ((TextBox)e.Item.Cells[6].Controls[0]).Text;

int upCatId = int.Parse(e.Item.Cells[7].Text);

string upImage = ((TextBox)e.Item.Cells[8].Controls[0]).Text;

3.Delete the row that is being updated (see the example in the preceding section).

4.Create a new DataRow and populate it with the new data.

DataRow dr = Dt.NewRow(); dr["isbn"] = upISBN; dr["author"] = upAuthor; dr["price"] = upPrice; dr["title"] = upTitle;

dr["description"] = upDescription; dr["id"] = upCatId;

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

543

dr["imgSrc"] = upImage;

Insert the new DataRow:

Dt.Rows.Add(dr);

5.Resync the DataGrid with the DataView (see the example in the preceding section).

To update the database, simply call the Web method sellerAdmin.updateItem, passing it the new data.

localhost.sellerAdmin newData = new localhost.sellerAdmin();

newData.updateItem(upISBN,upAuthor,upPrice,upTitle,upDescription,

upImage,upCatId);

One limitation of the DataGrid is that it doesn’t provide a UI for adding new records.We will handle this case by creating another page: addBook.aspx.

Creating the addBook Page (addBook.aspx)

The addBook is another fairly straightforward page. It provides a UI where the site administrator can fill out a simple HTML form and submits.This data is handled by the code-behind page addBook.asmx.cs.This page simply passes the data to the database via the Web method sellerAdmin.addBook:

addNewBook = new localhost.sellerAdmin();

resultAdd = addNewBook.addItem(addISBN,addAuthor,addPrice,addTitle,addDescription, addPath,addCatId);

Customer Administration

In this section, we will develop the code that allows us to tie our customer administration interface to our Web Services (see Figure 12.23).

Creating the Customer Admin Section

This section of the site deals with user authentication, including creating a customer account and login.We use this to simulate order processing.

www.syngress.com

544 Chapter 12 • Creating an ADO.NET Shopping Cart

Figure 12.23 Customer Administration Page Group Overview

loginCustomer

 

.aspx

 

loginCustomer

 

.aspx.cs

 

updateCustomerInfo

newCustomer.aspx

.aspx

 

updateCustomerInfo

newCustomer

.aspx.cs

.aspx.cs

Customer Admin Pages

Creating the loginCustomer Page

We will use the same form layout as we did for the admin login described in the preceding section. One change we’ll implement is that we’ll call a Web Service to verify the login of the customer.

1.Make a call to the Web Service loginCustomer.This should be routine by now, but let’s look at the code to call the Web Service:

loggedCust = new WebReference1.loginCustomer();

2.Access the Web method validCustomer. Now we have access to all the methods contained in the class.

string resultId =

loggedCust.validCustomer(validEmail,validPassword);

3.Return a value.We can now check the value of the variable resultId and either grant the customer access or return an error message.

if(resultId == "-1")

{

loginLabel.Text = "Invalid Login please re-enter your password and email!";

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

545

}

else

{

loginLabel.Text ="Welcome";

Session["userId"] = int.Parse(resultId);

Server.Transfer((string)Session["return2Page"]);

}

Now we have the customer logged in to the site and they can go to any page without having to sign in again.

NOTE

We are using a session variable to track where the user is coming from when they are prompted to login. This will enable us to redirect them back to the page where they came from rather then sending them to some nonspecific page and having them navigate through the site from scratch.

Creating the updateCustomerInfo Page

We can now add a page that will let the customer update his or her information. This will be done identically to the example from site admin where we brought in all books and then enabled the site administrator to go through the books listed and delete, update, or add books at will. In this case, we will enable the customer to update only.

1.Select the row to update by using the RowFilter property of the

DataView.

2.Create a new DataRow Item and populate it with the changes (new Data).

3.Delete the row that is being updated.

4.Insert the new DataRow.

5.Resync the DataGrid with the DataView.

All five steps are the same as covered in earlier examples. Let’s look at the code one more time:

www.syngress.com

546 Chapter 12 • Creating an ADO.NET Shopping Cart

Dt = Customers.AllCustById((int)Session["userId"]).Tables["Customers"];

myView = new DataView(Dt);

myView.Sort = "CT_ID";

Set the DataTable value into the DataView:

custGrid.DataSource = myView;

custGrid.DataBind();

Set the data source of DataGrid:

myView.RowFilter = "CT_ID='"+upId+"'"; if (myView.Count > 0)

{

myView.Delete(0);

}

myView.RowFilter = "";

DataRow dr = Dt.NewRow(); dr[0] = upId;

dr[1] = upFName; dr[2] = upLName; dr[3] = upEmail; dr[4] = upPassword; Dt.Rows.Add(dr);

Delete the bad data row and the new one:

WebReference1.adminCustomer newData = new

WebReference1.adminCustomer();

newData.updateCust(upId,upFName,upLName,upEmail,upPassword);

Lastly, update the database by calling the Web service.

In the previous examples we have made extensive use of the DataGrid control for DataBinding DataSet information to the UI.We must admit we were a bit reluctant to use the DataGrid since it seemed reminiscent to the DataGrid Design Time Controls (DTCs). DTCs were included with many versions of FrontPage, Visual InterDev, and Office.They made it easy for novice developers to quickly create data driven Web sites. Lets just say DTCs had some drawbacks, to put it

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

547

politely! In the next two sections, ADOCatalog and XMLCart, we will use XSL/Transforms against XML data to produce our UI.This is accomplished by using the asp:xml server control as well as client side script and hidden asp:text controls.The ADOCatalog’s primary interfaces will return DataSet objects so it could be easily tied to a DataGrid control.We will leave that as an exercise for you.The XMLCart is primarily a wrapper class around the XmlDocument object. Its primary interfaces will return XmlDocument objects. Let’s get started!

Creating an ADOCatalog

In this section, we will develop the code that allows us to tie our catalog interface to our Web Services.We will store a DataSet in an Application variable to reduce the load on the database, perform copy, clone, import, create, and filter operations on ADO.NET DataSet objects, and use XML and Extensible Stylesheet Language Transformations (XSLT) to render data stored in a DataSet as HTML via the asp:xml server control.

In our ADOCart application, all database interaction is handled via Web Services. Since our “Books” data is fairly static, we can retrieve the data in a DataSet once and store that DataSet in an application-level variable.This reduces the database traffic, while still providing quick access to the data. Here is an overview of the process we will be following:

Load all Books data to an application variable:

Application["AllBooks"];

Create an instance of ADOCatalog (a.k.a., BookCatalog).

In Page_onload

Initialize the instance by passing it.

(DataSet)Application["AllBooks"];

Call BookCatalog.CatalogRange(0,5) to return the first five books.

Convert return data to XML.

Load XSLT.

Set Document and Transform properties of the asp:xml control.

www.syngress.com

548 Chapter 12 • Creating an ADO.NET Shopping Cart

Now, lets create the code.To store our data in an application object, open the Global.asax file. Add this to the Application_onstart method:

localhost.getBooks DataSource = new localhost.getBooks();

Application["AllBooks"] = DataSource.AllBooks();//DataSet

This will create an instance of the getBooks object called DataSource. Using this instance, we call the AllBooks method, which returns a DataSet.We then save the DataSet in an application-level variable, allbooks.

NOTE

localhost is a reference to the name of the Web Reference containing the getBooks Web Service proxy (getBooks.wsdl).

Now add a new page to the Web Application project (bookSourceUI). Name it start.aspx. Below the #endregion section in the WebForm1 class, we will create a new class called bookCatalog.

Creating the BookCatalog Class

The BookCatalog class will contain the following public methods: InitCatalog,

Catalog, CatalogItemDetails, CatalogRange, CatalogByCategory, and the private methods CatalogRangeByCategory, and CreateSummaryTable.The following is a rough prototype of the ADOCatalog class that we’ll be building in this section:

public class bookCatalog

{

protected WebReference1.getBooks DataSource; protected DataSet dsAllBooks;

protected DataTable dtSummary;

protected DataTable createSummaryTable(

int startPos, int range, int RecordCount) public DataSet catalog()

public void initCatalog(DataSet ds )

public DataSet catalogItemDetails( string book_isbn ) public DataSet catalogRange(int startPos, int range)

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

549

public DataSet catalogByCategory( int catId)

protected DataSet catalogRangeByCategory(

int startPos, int range, int catId, string book_isbn)

}

Creating the CreateSummaryTable Method

The CreateSummaryTable method creates a DataTable that contains summary information about the DataSet being returned.This data is used by the XSLT to display Metadata (i.e., viewing records 6 through 12 of 25). It is also useful when making a fetch next range of records call.

Based on the prototype, this method will take the parameters int startPos, int range, and int RecordCount and will return a DataTable. Let’s get started.

1. Create a new empty DataTable named “summary”.

DataTable dtSummary = new DataTable("Summary");

In the XSD schema this makes the DataTables parent

element a summary tag (i.e. <summary> )

2.Now add the Columns RecordCount, FirstItemIndex, and LastItemIndex to the Summary DataTable.

dtSummary.Columns.Add(

new DataColumn("RecordCount", typeof(int)));

dtSummary.Columns.Add(

new DataColumn("FirstItemIndex", typeof(int)));

dtSummary.Columns.Add(

new DataColumn("LastItemIndex", typeof(int)));

3. Create a new DataRow object and assign it to a new DataTable row.

DataRow drSummary;

drSummary = dtSummary.NewRow();

4. Populate the DataRow object and add it to the DataTable.

drSummary["RecordCount"]

= RecordCount;

drSummary["FirstItemIndex"] = startPos;

drSummary["LastItemIndex"] = startPos + range;

dtSummary.Rows.Add( drSummary );

www.syngress.com