cis-iis1.temple.educis-iis1.temple.edu/cis3309/hwa12...  · web viewactive server pages (asp) is a...

49
CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 4/27/2022 CIS 3309 ASP.NET Project (Final Project Part 3) Fall 2012 Written by Joe Jupin Version 9 March 30, 2011 Revised by Jessica Clark: April 19, 2012 by FLF: Nov 26, 2012 Introduction This project involves the construction of a Web-based transaction processing system implemented with a Web application. Active Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language (HTML) Web interface with an interactive executable coding language, producing dynamic Web pages used to build Web applications. The server compiles the presentable Web form (in pure HTML code) and returns the Web pages to the user’s Web browser. The purpose of this project is to introduce you to ASP.NET, the ASP programming interface in Visual Studio using Visual Basic .NET as the executable coding language. To make the most of the material that follows, you are urged to first read Chapters 1 and 2 of the Murach text Murach's ASP.NET 4.0 Web Programming with VB 2010 . The link to these Chapters is: http://www.murach.com/books/a4vb/chapters.htm . This document assumes that you have read this material. A Web server must have Microsoft’s Internet Information Services (IIS) or Windows Server 2000 or later installed and running to make use of ASP. A simple explanation of how ASP and IIS (or Windows Server) works from the perspective of a user is given below. Note that this material is covered in more detail in 1

Upload: trancong

Post on 05-Feb-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

CIS 3309 ASP.NET Project (Final Project Part 3)Fall 2012

Written by Joe Jupin Version 9 March 30, 2011Revised by Jessica Clark: April 19, 2012 by FLF: Nov 26, 2012

Introduction

This project involves the construction of a Web-based transaction processing system implemented with a Web application.

Active Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language (HTML) Web interface with an interactive executable coding language, producing dynamic Web pages used to build Web applications. The server compiles the presentable Web form (in pure HTML code) and returns the Web pages to the user’s Web browser.

The purpose of this project is to introduce you to ASP.NET, the ASP programming interface in Visual Studio using Visual Basic .NET as the executable coding language. To make the most of the material that follows, you are urged to first read Chapters 1 and 2 of the Murach text Murach's ASP.NET 4.0 Web Programmingwith VB 2010. The link to these Chapters is:

http://www.murach.com/books/a4vb/chapters.htm.

This document assumes that you have read this material. A Web server must have Microsoft’s Internet Information Services (IIS) or Windows Server 2000 or later installed and running to make use of ASP. A simple explanation of how ASP and IIS (or Windows Server) works from the perspective of a user is given below. Note that this material is covered in more detail in the Murach ASP.NET text and the Lecture Notes for CIS 3309,Appendix G, Parts A and B.

The user enters a URL (Universal Resource Locator) string in the URL bar of the browser or clicks a hyperlink on a Web page to navigate to an ASP page

The application server (IIS in this case) accepts a request from the user’s browser by accessing the ASP code in the Web form specified in the URL

The server processes the request by interpreting the ASP code and compiling the VB .NET code behind (in our case) for compilation and execution.

The server also compiles the presentable Web code producing an HTML page that can be rendered and processed by a browser.

Returns these dynamic Web pages to the user’s Web browser

Exercise 1: Do not go any further in this document until you have read Chapters 1 and 2 in the Murach ASP.NET 4.0 book.

1

Page 2: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

The user can then use the Web form’s controls (textboxes, buttons, etc.) to pass data and requests back to the server. This can further modify the appearance and functionality of the current form or send data and instructions to control the generation of new forms.

The transaction processing system you will build will extend the Book, CD and DVD Shop project Parts 1 and 2 by creating a Web site that retrieves data from the product table in a database, presents some information about the product, and saves selected products to a shopping cart. Figure 1 shows the design flow chart for the Web site in terms of the web pages (forms) involved in the system.

Figure 1: Web site design

*Note: In this project, the Default page IS the Login page.

2

Page 3: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Create an ASP.Net Project

To build the transaction processing system, we will have to build a new kind of project in Visual Studio, an ASP.NET Web Site project. To do this, you follow the steps listed below. ASP.NET will create a default application and we will modify it and add new pages to process data and present information to the user about the shop’s Book, CD and DVD products.

We begin by opening Visual Studio and then following along with the steps outlined next.

1. In the File menu, click New Website

2. When the New Web Site window pops up, click on

Select ASP.NET Web Site

Rename the project to “BookCdDvdWeb” in “File System” (Don’t change the path -- just the ending filename). DO NOT FORGET TO RENAME YOUR PROJECT, PLEASE

3. Next select VB as the coding language

4. Now you can close the New Web Site window and create the , Click OK

Add Folders and Existing Items

Some of the work you need has already been completed. You can view the source code in your zip folder (provided by the lab assistant) for an explanation of their purpose because they are well commented (hint). Follow the steps below to add necessary folders and existing items to the project.

As you work your way through this document, be sure to save your work after completing each stage or even more often if need be.

ASP.NET has special purpose folders. When the project was created, the “App_Data” folder was automatically created. This is a special folder for data files. If you drag and drop an Access database file on this folder’s icon, the file will be copied to the “App_Data” folder and the database will automatically be included in the project. The “App_Code” folder is for existing code, such as classes, to be used in the project. If you drag and drop a .vb file on its icon, the VB code will automatically be included in the project and the files will be copied to the “App_Code” folder.

3

Page 4: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

1. Add an ASP.Net folder: “App_Code”a. Right click on the root folder and select Add ASP.NET Folder ->

“App_Code”

2. Create a new folder called “Images”

3. Drag and drop all your images onto the Images directory icon.

4. Copy the databases included in the file to the “App_Data” folder (Drag and drop the DB file onto the App_Data icon)

5. Copy the class files in zip file “App_Code” folder to the “App_Code” folder in your solution (Again, drag and drop)

Create New aspx Pages

We now use the Add New Item Wizard. This Wizard is very much like the other Add New wizards we used in VB, except that the templates are limited to those that work in ASP.NET.

1. Add a new web form called “Order.aspx”a. Right click on the root folder at the top of the Solution Explorerb. Select “Add New Item”. In the “Add window …”

i. Select “Web Form” from “Templates”ii. Rename the form to “Order.aspx”iii. Language should be VBiv. “Place code in separate file” should be checkedv. Click “Add”

2. Add a new web form called “Search.aspx” (as above)

3. Add a new web form called “CustomerRegistration.aspx”

4. Add a new web form called “Login.aspx”

5. Add a new web form called “Cart.aspx”

6. Add a new web form called “Checkout.aspx”

7. Add a new class called “DBConnect”

Note that these web forms correspond to the forms shown in Figure 1.

4

Page 5: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Introduction to Web Pages – Setting the Start Page and Code and Design Views

Figure 2 illustrates a view of the Search web page for this project. (In the next section we will see how to create this page, but we show it here to illustrate and briefly discuss the sub windows that appear.) Double click on the Search.aspx bar in the Solution Explorer to see the Search form itself (currently just a skeleton blank form in your project). Note that there are two views of the form – the design View (currently blank) and the Source View which shows the skeleton aspx file created automatically when you create a web form. More on this in a minute.

Figure 2: The Search.aspx form in design view

ASP.NET’s Web form controls are similar to those used in VB. The Toolbox contains many of the same controls that are included in the VB Toolbox shown on the left in Figure 1. The Solution Explorer and Properties window are also very similar to VB and should also be located in the typical configuration and position.

Figure 2 shows the Solution Explorer on the right side of the IDE with the Properties box in one of the tabs under it. The default and other event handlers are added in the same manner as was done in your earlier projects. If you double click a button, ASP.NET creates an On-click event handler for the button. The text property for the label, textbox or button sets the text that is displayed on these controls. You can add

5

Page 6: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

HTML text by clicking on the form. The typed text will appear at the cursor. You can format this text in the same way as in Word and FrontPage. Notice that there are text formatting tools on the menu bar. You will want to experiment with these tools

The image in Figure 3 shows the ASP code for the Search Web form in Source view. You can see the ASP source code by clicking the Source button on the lower left side of the IDE. You can tweak the Search Web form by editing this code (BUT JUST BE VERY CAREFUL IF YOU DO). This code is very similar to regular HTML except for the ASP tags interspersed in the code text. Note carefully the relationship between the design view of the form in Figure 2 and the source code view in Figure 3.

Figure 3: ASP Source (HTML) code for the Search.aspx Page

Exercise 2: Summarize the purpose of HTML code that appears between the <body></body> tags. Summarize the purpose of the code that appears between the <div></div> tags.

6

Page 7: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Executing ASP Code

There are two ways to execute code in ASP: server-side or client-side. The server-side code is written in a programming language, such as C# or VB, and the client-side code is usually JavaScript. If you look at the controls on the source view in Figure 3, you see a term: runat = “server ”. It is easy to understand what this means for any of these controls. The server-side code can be embedded in the body of the ASP page by using special markers: <% and %> with methods and variables in a <script runat=”server”> (Code goes between these script tags) </script>. This is usually done when the ASP page is hand-coded in a text editor.

The preferred ASP.NET way to specify server code is to have the code in a separate file. For example, the VB code corresponding to Search.aspx is in the “Search.aspx.vb” code-behind file.

Adding Controls and Text to Web Pages

We are now ready to begin to add controls, text, color, etc to a blank web page. The goal is to achieve the Default web page shown in Figure 5. Make sure you are viewing the Default.aspx page in Design View.

Note that by default, all entries you make on a web form are made in flow layout. In flow layout, everything you enter on a web form is entered left to right, top to bottom. In so doing, the position of the controls and text can change depending on the size of the browser window and the resolution of the display. Flow layout is similar to what you are used to in working on a word processing document of creating a static web form using HTML. You can learn a bit more about flow layout by visiting the section on “How to use flow layout” of the ASP.NET 4.0 text book.

Exercise 3: Reread the material in the Murach ASP.NET 4.0 text on Flow Layout editing (See pages 42-50). Also read Pages 60-62 on how to use validators and a little on how they work.

Validators are ASP.NET objects that perform client-side validation. That is to say, they "write" javascript functions for you. So when you place the Required Field Validator on the form and set the Control to Validate property, a javascript function is written to validate that control. This will execute before any trips to the server are made, and prevent server trips until the control input is valid. For some, it is just as easy to write the javascript instead.

7

Page 8: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Figure 5: Customer Registration Page

1. Place controls on the Customer Registration form as shown in Figure 6.

a. The top line and the second line are HTML text.

b. There is 1 label called lblUsername. This will be used to display the username entered on the previous page.

c. There are 7 labels and 7 textboxes controls: (lblFirstName txtFirstName), (lblLastName txtLastName), (lblAddress txtAddress), (lblCity txtCity), (lblState txtState), (lblZipCode txtZipCode) and (lblPhone txtPhone).

d. The navy blue text is HTML text.

e. There are 7 RequiredFieldValidator controls- one next to each textbox. These are found in the Validation dropdown of the Toolbox. For each one, set the Error Message property to “*Required”, and the ControlToValidate property to the name of the textbox that is next to it.

f. Place 2 buttons (btnSubmit and btnExit) on the form.

2. Set appropriate page title in the HTML head section.

Exercise 4: Summarize what happens when a button is clicked on a web page.

8

Page 9: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

The Login page is in Figure 6.

Figure 6: Login Page

1. Place controls on the Login form as shown in Figure 6.

a. The top line, the second line and the navy blue text are HTML text.

b. There is 1 label with empty text property. (lblMessage). This will be used to show error messages if necessary.

c. There are 2 labels and 2 textboxes in the group of controls: (lblUserID, txtUserID) and (lblPassword, txtPassword).

d. Place a RadioButtonList (radio) on the form. Click on the smart tag, and select Edit Items. Add 2 new Items: (text=Returning Customer, value=exist), (text=New Customer, value=new).

e. Place 2 buttons (btnSubmit and btnExit) on the form.

2. Set appropriate page title in the HTML head section.

The Search page is in Figure 8.

9

Page 10: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Figure 4: The Search.aspx page

1. Place controls on the Search form as shown in Figure 8.

a. The top line is HTML text which you can enter and arrange by clicking on the form and typing.

b. The second line is a label (lblSearchTerm), a textbox (txtSearchTerm) and a button (btnSearchTerm).

c. Place 3 buttons (btnGoToCart, btnCheckOut and btnLogout) on the bottom of the form.

2. Set appropriate page title in the HTML head section.

The Order Page is in Figure 8.

10

Page 11: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Figure 8: The Order.aspx page

1. Place controls on the Order form as shown in Figure 8.

a. The top line is HTML text. The second line is a label (lblMessage).

b. On the third line, the object is a listbox (lstFound).

c. The fifth to eighth lines are labels (lblUPC, lblTitle, lblPrice and lblDescription).

d. The ninth line is an image (imgProduct).

e. The tenth line has a label (lblQuantity) and a textbox (txtQuantity).

f. The eleventh line has two buttons (btnAddToCart and btnGoToCart).

g. The twelfth line has three buttons (btnContinue), (btnCheckOut) and (btnLogout).

2. Set appropriate page title in the HTML head section.

11

Page 12: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

We now continue our preliminary work on the forms pages that we need for this project by creating the Cart Page, shown in Figure 9. We begin by selecting the Cart.aspx bar in Solution Explorer.

Figure 9: The Cart.aspx page

1. Place controls on the Cart form as shown in Figure 9.

a. The top line is HTML text.

b. The second line is a label (lblMessage).

c. The third line has a Data GridView object (dgvCart)

d. The fourth to sixth lines are labels (lblSubtotal), (lblTax) and (lblTotal).

e. The remaining lines contain four buttons: btnCheckOut, btnContinue, btnEmpty, and btnLogout.

2. Click on the GridView’s Smart Tag and select Auto Format, and select Classic as the scheme.

3. Click the Smart Tag again and select Edit Columns. Click the + next to CommandField in the Available fields listbox. Select Delete and click on the Add

12

Page 13: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

button. Select Delete in the Selected fields listbox and the CommandField Properties will appear on the right. Select Button for ButtonType in properties. Click OK.

4. Set appropriate page title in the HTML head section.

Exercise 5: Look up the data grid views and write a summary of the purpose of the cells in the data grid view in Figure 9.

Now we can complete our work on the last page that is required for the project, by creating the Checkout Page.

Figure 5: The Checkout.aspx page

1. Place controls on the Checkout form as shown in Figure 10.

a. The top line is a label (lblTitle) with a font size XX-Large.

b. The second line is a Data GridView (dgvCart).

13

Page 14: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

c. The third line to fifth lines are labels (lblSubtotal), (lblTax) and (lblTotal).

d. The sixth line is a label (lblCardType) and a drop-down list (ddlCardType).

e. The seventh line is a label (lblCardHolder) and a textbox (txtCardHolder).

f. The eighth line is a label (lblCardNumber) and a textbox (txtCardNumber).

g. The ninth is HTML text.

h. The tenth line is a button (btnPlaceOrder).

i. The eleventh is two buttons (btnEmpty) and (btnGoToCart).

j. The twelfth is two buttons (btnContinue) and (btnLogout).

2. Set appropriate page title in the HTML head section.

Coding the Login page

The Login page has both client and server side code. The purpose for this page is to validate a customer’s credentials. The client side code is Javascript that is placed between the head and body sections in the HTML code in the Login.aspx file. This code performs customer UserID and Password validation for conditions that define acceptable string values. The UserID should be at least 5 characters and begin with a letter and the Password must be at least 8 characters, begin with a letter or number and have at least one upper case letter, one lower case letter and one number. The script uses a construct called a regular expression as a comparator for acceptable strings. Look at this web site for more information on regular expressions: http://www.regular-expressions.info/. This is a very efficient method to validate input strings with constraints.

1. Set Options Strict and Explicit to On.

2. Paste the script below between the end of the head section and before the body in source view in the Login.aspx file:

<script type="text/javascript" language="javascript">

// Function to validate UserID and Password on client sidefunction validate(){ // Get UserID from txtUserID textbox and validate its structure var myUserID = document.getElementById("<%=txtUserID.ClientID%>").value; // Set a regular expression to begin with a letter and >= 5 characters var reUserID = /^[A-Za-z]\w{4,}$/;

14

Page 15: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

// Test UserID against regular expression. test is Javascript function // that runs against real expressions if (!reUserID.test(myUserID)) { // Bad UserID alert alert("Please enter a valid User ID!"); // Set focus to txtUserID document.getElementById("<%=txtUserID.ClientID%>").focus(); // Return bad UserID return false; } // Check for STRONG Password // Get Password from txtPassword textbox var myPassword=document.getElementById("<%=txtPassword.ClientID%>").value; // Set regular expression to begin with cap or small letter or number // and be >= 8 characters var rePassword1 = /^[A-Za-z0-9]\w{7,}$/; // Set another regular expression to check for at least 1 lower case // and 1 upper case letter, and 1 number var rePassword2 = /^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$/; // Check txtPassword against rePassword1 if (!rePassword1.test(myPassword)) { // Bad Password alert alert("Please enter a valid password! - Must have 8 characters"); // Set focus to txtPassword document.getElementById("<%=txtPassword.ClientID%>").focus(); // Return bad Password return false; } // Check txtPassword against rePassword2 if (!rePassword2.test(myPassword)) { // Bad Password alert alert("Please enter a valid password! - Must have a upper case, " _ + "lower case and a number"); // Set focus to txtPassword document.getElementById("<%=txtPassword.ClientID%>").focus(); // Return bad Password return false;

} // Everything okay - return true return true;}

</script>

The <script …> and </script> tags mark the beginning and end of the Javascript section of the HTML document. The code that you pasted into the Login form as Javascript will check for several things. First it checks (using reUserID ) to make sure that the user login ID begins with a letter and contains at least 4 other characters. The symbol \w indicates that any “word” (a sequence of 0 or more characters in the set consisting of alphanumeric characters and the underscore [A-Za-z0-9_]) can follow the

15

Page 16: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

first letter. The symbols {4,} following the \w further restricts this string to consist of at least 4 characters with no specified maximum.

The above code then checks (using rePassword1) to ensure that the user password begins with a letter and has at least 8 characters. If a strong password is used instead, it must also have at least one lower case letter, at least one upper case letter and at least one number. The Regex code for a strong password is:

“/^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$/”.

This is a more difficult string to decipher, but you can get help if you are interested at the website shown at the beginning of this discussion. The symbol sequence w* indicates the appearance of 0 or more “words” and the sequence ?= has a special meaning marking a “word boundary” (the end of one word and the start of a new one).

3. Create a page load event for the Login.aspx page and paste this code into it:

' Set a client side javascript validate to run before server code is executedbtnSubmit.Attributes.Add("onclick", "return validate()")'if an error message is returned, display it in the message label.lblMessage.Text = Session("errormessage")

This code causes the Javascript to execute before the code in the btnSubmit event handler. If a false value is returned by the Javascript, the event handler is blocked from execution. A true return value allows the execution of the event handler.

4. Create an event handler for btnSubmit and paste the following code:

'Determine if customer is new or existingIf radio.SelectedValue = "new" Then Session.Add("customertype", "new")ElseIf radio.SelectedValue = "exist" Then Session.Add("customertype", "exist")Else 'no radio button selected. lblMessage.Text = "Please indicate if you are a returning or new customer." Exit SubEnd If

'If the session variable item userID does not exist, create itIf Session("userID") Is Nothing Then Session.Add("userID", txtUserID.Text)Else Session("userID") = txtUserID.TextEnd If

'If the session variable item password does not exist, create itIf Session("password") Is Nothing Then Session.Add("password", txtPassword.Text)

Else

16

Page 17: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Session("password") = txtPassword.TextEnd If

'Go to registration pageResponse.Redirect("CustomerRegistration.aspx")

Look at the comments to see the purpose for this code.

Exercise 6: Look up Session.Add and describe what happens when the line of code

Session.Add("password", txtPassword.Text)

Is executed. Saving Session data is disucssed in your ASP.NET text, pp.12-13.

5. Create an event handler for btnExit and paste the following code:

' Go to Login pageResponse.Redirect("Login.aspx")

That’s it for the Login.aspx page.

Exercise 7: Look up Response.Redirect and describe what occurs when the line of code

Response.Redirect("Login.aspx")

Is executed.

Coding the Customer Registration page

The purpose for this page is to facilitate the capture of customer account data. The validators check to see that all input controls are filled. The UserID is the primary key and duplicate values are not allowed because each user has to be unique and insertion of a duplicate UserID will cause a database exception. In the login page code, we validated the structure of a user ID and password. At this point, either validate a returning user against a database of user data (in the Customer table), or we enter a new user into the database.

1. Set Options Strict and Explicit to On.

2. Add the following Imports statement to include data libraries

Imports System.Data

17

Page 18: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Exercise 8: Describe the purpose of the imports statement appearing directly above (previous page).

3. Add the following module-level code to create reference variables for the database access to follow. The objects (to be created later) of these types will be used to enable us to access full tables of a database as internal dataSets.

Dim objDS As System.Data.DataSetDim objDT As System.Data.DataTableDim objDR As System.Data.DataRowDim objDB As New DBConnect

4. Add the following code to the page load event. Look up the method getDataSet to see what is does.

If Not IsPostBack Then 'first page load objDB = New DBConnect '(create and save connection object) Session.Add("objDB", objDB)Else 'is postback (not first page load – get saved connection object) objDB = Session("objDB")End If

' Check data base for UserID and PasswordobjDS = objDB.getDataSet("SELECT * FROM tblCustomer WHERE fldLoginID = '" _ & Session("userID") & "'")If objDS.Tables(0).Rows.Count = 0 Then 'no userID match If Session("customertype") = "exist" Then 'A match is required but no match was found Session.Add("errormessage", "Login ID not found.") Response.Redirect("Login.aspx") 'else- no match requested, no match found. OK. End If 'End inner if (for an existing customerElse 'userID match found If CheckIDPass(objDS) = False Then 'password match incorrect. Response.Redirect("Login.aspx") Else 'userID and password correct. load information into form. lblUsername.Text = objDS.Tables(0).Rows(0).Item(0).ToString txtFirstName.Text = objDS.Tables(0).Rows(0).Item(3).ToString txtLastName.Text = objDS.Tables(0).Rows(0).Item(2).ToString txtAddress.Text = objDS.Tables(0).Rows(0).Item(4).ToString txtCity.Text = objDS.Tables(0).Rows(0).Item(5).ToString txtState.Text = objDS.Tables(0).Rows(0).Item(6).ToString txtZipCode.Text = objDS.Tables(0).Rows(0).Item(7).ToString txtPhone.Text = objDS.Tables(0).Rows(0).Item(8).ToString End IfEnd If

18

Page 19: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

5. Create a Sub called MakeCart() and paste the code:

' Make a new DataTable object called Cart. Name columns and define typesobjDT = New System.Data.DataTable("Cart")

' Add a column to contain a unique IDobjDT.Columns.Add("ID", GetType(Integer))' Set ID column to automatically incrementobjDT.Columns("ID").AutoIncrement = True' Set ID to start at 1objDT.Columns("ID").AutoIncrementSeed = 1

' Add column definitions - cloumn names and types of data' Add a column to contain the quantity to be purchasedobjDT.Columns.Add("Quantity", GetType(Integer))' Add a column to contain the UPC (The type of the UPC is a string)objDT.Columns.Add("UPC", GetType(String))objDT.Columns.Add("Title", GetType(String))objDT.Columns.Add("Price", GetType(Double))objDT.Columns.Add("Cost", GetType(Double))

' Place the Cart in the Session variableSession("Cart") = objDT

This code creates the Cart and places it in the Session object. It will remain there until the Cart is deleted or the Session is deleted or expires.

Exercise 9: Go to your favorite shopping site and let it create a cart for you. Put something in the cart from any order page, verify that the cart is correct (which should take you to another page), and then go back to the order page. Is the cart still there? How does this work?

Exercise 10: Now log out of the shopping site you are in and then log back in. Are the things you placed in the cart still there? How does this work?

Exercise 11: Look up the method getDataSet to see what it is supposed to do.

6. Create an event handler for btnSubmit and paste this code:

' Save customer information If WriteToDB() = False Then Exit Sub End If

' Create Cart to contain items for purchase MakeCart() ' Go to search page Response.Redirect("Search.aspx")

19

Page 20: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

7. Create a boolean function WriteToDB and paste the following code:

' Create an SQL insert string Dim sqlString As String = "" If Session("customertype") = "new" Then sqlString = "INSERT INTO tblCustomer VALUES( " sqlString += "'" + Session("userID") + "', " sqlString += "'" + Session("password") + "', " sqlString += "'" + txtLastName.Text + "', " sqlString += "'" + txtFirstName.Text + "', " sqlString += "'" + txtAddress.Text + "', " sqlString += "'" + txtCity.Text + "', " sqlString += "'" + txtState.Text + "', " sqlString += "'" + txtZipCode.Text + "', " sqlString += "'" + txtPhone.Text + "')" Else 'customertype = existing sqlString = "UPDATE tblCustomer SET " & _ "fldLastName = '" & txtLastName.Text & "', " & _ "fldFirstName = '" & txtFirstName.Text & "', " & _ "fldAddress = '" & txtAddress.Text & "', " & _ "fldCity = '" & txtState.Text & "', " & _ "fldState = '" & txtState.Text & "', " & _ "fldZipCode = '" & txtZipCode.Text & "', " & _ "fldPhone = '" & txtPhone.Text & "' WHERE " & _ "fldLoginID = '" & Session("userID") & "'" End If

'Update and check that insert is successful If objDB.doUpdate(sqlString) = -1 Then lblUsername.Text = "Unable to commit to database. Try again later." Return False End If 'Everything okay - return true Return True

Exercise 12: Look up the method doUpdate to see what it is supposed to do.

8. Create a function called CheckIDPass and paste the code:

Protected Function CheckIDPass(ByRef objDS As DataSet) As Boolean If Session("password") <> objDS.Tables(0).Rows(0).Item(1).ToString Then 'password incorrect Session.Add("errormessage", "Password Incorrect.") Return False End If 'If all ops pass, return true Session.Remove("message") Return TrueEnd Function

20

Page 21: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

9. Add the following code to the btnExit click event handler:

Session.Clear()Response.Redirect("Login.aspx")

Exercise 13: What is being referenced by the line of code

objDS.Tables(0).Rows(0).Item(1).ToString

How do you know?

That’s it for CustomerRegistration.aspx.

Coding the Search page

The Search.aspx page accepts a search term from the user on the client machine and processes the request on the server machine. The search term is typed into the textbox and is sent to the server when the user clicks the button. The code below is the button click event handler code. The first line creates a string to cause the server to send the user to the Order.aspx page. The ‘?’ marks the beginning of the query string, which will be “?SearchTerm=matrix” if the user typed matrix in the textbox. The complete string ‘s’ will be “Order.aspx?SearchTerm=matrix”. The next line sends the query string to Order.aspx and the compiled Order.aspx page to the client machine.

1. Set Options Strict and Explicit to On.

2. Create a page load event and paste:

' If the session variable item userID does not exist, loginIf Session("userID") Is Nothing ThenResponse.Redirect("Login.aspx")End If

3. Create a button click event for “btnSearchTerm” and paste the following code into it:

' Create a query string that contains the search criteria in the' txtSearchTerm textbox and redirect to the Order page.Dim s As String = "Order.aspx?SearchTerm=" + txtSearchTerm.TextResponse.Redirect(s)

4. Create an event handler for btnGoToCart and paste:

' Got to cart pageResponse.Redirect("Cart.aspx")

21

Page 22: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

5. Create an event handler for btnCheckOut and paste:

' Got to check out pageResponse.Redirect("CheckOut.aspx")

6. Create an event handler for btnLogout

' Clear all data for this sessionSession.Clear()' Go to Login pageResponse.Redirect("Login.aspx")

7. Set Options Strict and Explicit to On.

In case you are wondering, this is how we will eventually get the string that follows the ? embedded into the WHERE clause of an Access database query. We will do this next.

Exercise 14: It the condition (below) is true what does this mean?

Session("userID") Is Nothing

Coding the Order page

Once an application generates a web page and sends it back to the client, it is done and the application “ends.” This means that the values of any variables or control properties are lost after the web page is generated. In the jargon (also known as “terminology”) this is another way of saying that HTTP is a stateless system. That is, it will not maintain any state values across application executions. If we have certain variables or control parameters we need to save, we have to do it ourselves. Fortunately, as we have repeatedly seen already, ASP provides mechanisms for doing just that.

ASP has a special type of data called a session variable. A session variable is a collection object that is used to temporarily store references to other objects. It stays in scope until a client session ends. In other words, a session variable retains its “state” across executions of an application. With but a moment’s consideration, it should be pretty clear that our Cart is an example of a variable whose state needs to be maintain across applications. The “MakeCart” function creates an object called “Cart” in the current user’s session variable if it does not already exist. Notice that the reference to the cart is added to the session object. The type of the referenced object is System.Data.DataTable, which is instantiated with the New keyword. So, in this case, the entire cart is saved across application. How does this work?

Each client accessing web pages (using a web application such as ASP) at any given time is identified whenever they access the Web application because they are given a

22

Page 23: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

unique ID during their first request to the server. The “Page_Load” event controls which form controls are displayed and the data from the previous query that is copied to the controls. The If statement has a “IsPostBack” term. This term is false on the first access of this page from the “Search.aspx” page and true for all subsequent accesses, in which the page accesses itself. The “GetSelectedProduct” function gets the data for the selected item in the listbox. It reduces the query results by filtering them into a view containing only the selected product and packaging the data into a Product instance, which is returned to the calling function. The “AddToCart” adds items to the Cart object in the session variable.

1. Set the text property for “txtQuantity” to 1.

2. Set Options Strict and Explicit to On.

3. Add the following Imports statement to the very top (first line) of the file “Order.aspx.vb”:

Imports System.Data

4. Add the following modular variables under the Imports statement:

' The current selected product in the list box Private SelectedProduct As Product

' Create DataTable and DataRow objects Dim objDT As System.Data.DataTable Dim objDS As System.Data.DataSet Dim objDR As System.Data.DataRow

5. Copy the following code to “Order.aspx.vb”.

' Page load event - changes the displayed item when the page is reloaded ' based on the selected item in the list box of found items Protected Sub Page_Load(ByVal sender As Object, ByVal e As _ System.EventArgs) Handles Me.Load ' If this is a postback, display the list box selected item ' Else hide the display area If IsPostBack Then SelectedProduct = Me.GetSelectedProduct() lblUPC.Text = SelectedProduct.productUPC lblTitle.Text = SelectedProduct.productTitle lblPrice.Text = FormatCurrency(SelectedProduct.productPrice) lblDescription.Text = SelectedProduct.productDescription imgProduct.ImageUrl = "Images/" & SelectedProduct.productImage lblUPC.Visible = True lblTitle.Visible = True lblPrice.Visible = True lblDescription.Visible = True

23

Page 24: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

imgProduct.Visible = True lblQuantity.Visible = True txtQuantity.Visible = True btnAddToCart.Visible = True btnGoToCart.Visible = True Else 'Not postback - get and save list of all products in a DataSet

objDS = Session("objDB").getDataSet("SELECT * FROM tblProduct") 'Set dataset as source of listbox and bind it lstFound.DataSource = objDS.Tables(0) lstFound.DataTextField = "fldTitle" lstFound.DataValueField = "fldUPC" lstFound.DataBind() lblUPC.Visible = False lblTitle.Visible = False lblPrice.Visible = False lblDescription.Visible = False imgProduct.Visible = False lblQuantity.Visible = False txtQuantity.Visible = False btnAddToCart.Visible = False btnGoToCart.Visible = False End If End Sub

' Get the data from the item selected in the list box Private Function GetSelectedProduct() As Product ' Get the dataset of products corresponding to the selection objDS = Session("objDB").getDataSet _ ("SELECT * FROM tblProduct WHERE fldUPC = '" & _ lstFound.SelectedValue & "'") objDR = objDS.Tables(0).Rows(0) ' Instantiate the product Dim thisProduct As New Product ' Copy the view's data to the product thisProduct.productUPC = objDR.Item(0).ToString thisProduct.productTitle = objDR.Item(3).ToString thisProduct.productPrice = CDbl(objDR.Item(1).ToString) thisProduct.productDescription = objDR.Item(7).ToString thisProduct.productImage = objDR.Item(6).ToString Return thisProduct End Function

' Place an item in the cart Private Sub AddToCart(ByVal CartItem As CartItem) objDT = CType(Session("Cart"), DataTable)

Dim blnMatch As Boolean = False

For Each Me.objDR In objDT.Rows If CStr(objDR("UPC")) = SelectedProduct.productUPC Then objDR("Quantity") = CInt(objDR("Quantity")) + _ CInt(txtQuantity.Text)

24

Page 25: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

blnMatch = True Exit For End If Next

If Not blnMatch Then objDR = objDT.NewRow objDR("Quantity") = CInt(txtQuantity.Text) objDR("UPC") = SelectedProduct.productUPC objDR("Title") = SelectedProduct.productTitle objDR("Price") = CDbl(SelectedProduct.productPrice) objDR("Cost") = CDbl(CDbl(SelectedProduct.productPrice) * _ CInt(txtQuantity.Text)) objDT.Rows.Add(objDR) End If Session("Cart") = objDT End Sub

Continuing with the “Order.aspx.vb form VB code, we note that the event handler for “btnAddToCart” places an item, selected in the listbox, in the Cart (which is a SortedList) object in the session variable. Then the client is automatically redirected to the “Cart.aspx” form so that the contents of the cart may be viewed.

Exercise 15: What do the following lines of code do? Perhaps you will need to run your project in order to answer this? Hint: How is the listbox populated?

'get list of all products from database and save in a DataSetobjDS = Session("objDB").getDataSet("SELECT * FROM tblProduct")'set dataset as source of listbox and bind itlstFound.DataSource = objDS.Tables(0)lstFound.DataTextField = "fldTitle"lstFound.DataValueField = "fldUPC"lstFound.DataBind()

Exercise 16: What does the following line of code do?

objDT = CType(Session("Cart"), DataTable)

6. Create a click event for “btnAddToCart” and insert the following code to it:

If Page.IsValid Then ' Copy data to an item Dim CartItem As New CartItem CartItem.thisProduct = SelectedProduct CartItem.thisQuantity = CType(txtQuantity.Text, Integer) ' Place it in the cart Me.AddToCart(CartItem) ' Got to cart page Response.Redirect("Cart.aspx")

25

Page 26: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

End If

The code for the “btnGoToCart” event handler simply redirects the client to the Cart.aspx page.

Exercise 17: What does IsValid (above code) do?

7. Create a click event for “btnGoToCart” and insert the following code:

' Go to cart pageResponse.Redirect("Cart.aspx")

8. Create an event handler for btnContinue and paste:

' Go to searchResponse.Redirect("Search.aspx")

9. Create an event handler for btnCheckOut and paste:

' Go to check out pageResponse.Redirect("CheckOut.aspx")

10.Create an event handler for btnLogout and paste:

' Clear all data for this sessionSession.Clear()' Go to login pageResponse.Redirect("Login.aspx")

Coding the Cart page

The Cart.aspx page uses the “Page_Load” event handler to populate the GridView with the contents of the Cart object in the session variable. “GetCart” function is as previously described and the “DisplayCart” function copies the products into the listbox.

1. Set Options Strict and Explicit to On.

2. Add the following Imports statement to the Cart.aspx.vb file:

' Import Data NamespaceImports System.Data

26

Page 27: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

3. Add the following module-level code to the VB code file for Cart.aspx.vb:

' Create DataTable and DateRow objectsDim objDT As System.Data.DataTableDim objDR As System.Data.DataRow

4. Copy the following code into the “Cart.aspx.vb” file:

' Page load event handler to fill GridView with cart itemsProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

' If the session variable item userID does not exist, login If Session("userID") Is Nothing Then Response.Redirect("Login.aspx") End If

objDT = CType(Session("Cart"), DataTable)

dgvCart.DataSource = objDT dgvCart.DataBind()

SetTotals()

End Sub

' Calculate Subtotal, Tax and TotalPrivate Sub SetTotals()

Dim intCounter As Integer

Dim dblSubtotal As Double

If objDT.Rows.Count = 0 Then lblSubtotal.Text = "Subtotal: " + (0).ToString("C") lblTax.Text = "Tax: " + (0).ToString("C") lblTotal.Text = "Total: " + (0).ToString("C") Exit Sub End If

For intCounter = 0 To objDT.Rows.Count - 1 objDR = objDT.Rows(intCounter) dblSubtotal += (CDbl(objDR("Price")) * CDbl(objDR("Quantity"))) Next

Dim dblTax = dblSubtotal * 0.08

lblSubtotal.Text = "Subtotal: " + dblSubtotal.ToString("C") lblTax.Text = "Tax: " + dblTax.ToString("C") lblTotal.Text = "Total: " + (dblSubtotal + dblTax).ToString("C")

End Sub

27

Page 28: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

5. Add an event handler for the GridView Delete button:

' This ia a special event handler that detects when one of' the delete buttons in the GridView is clicked.' It uses the index of the clicked button to delete' the peoper row.Protected Sub dgvCart_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles dgvCart.RowDeleting

objDT = CType(Session("Cart"), DataTable) objDT.Rows(e.RowIndex).Delete() Session("Cart") = objDT

dgvCart.DataSource = objDT dgvCart.DataBind()

SetTotals()

End Sub

This code enables the deletion of products in the cart. The click event for “btnRemove” removes items from the cart.

The click event for “btnEmpty” empties the cart.

Exercise 18: What does the following code do (in detail – step by step).

objDT = CType(Session("Cart"), DataTable) objDT.Rows(e.RowIndex).Delete() Session("Cart") = objDT

dgvCart.DataSource = objDT dgvCart.DataBind()

6. Create a click event handler for the “btnEmpty” button and paste the following code:

objDT = CType(Session("Cart"), DataTable) objDT.Clear()

dgvCart.DataSource = objDT dgvCart.DataBind()

Session("Cart") = objDT SetTotals()

The click event for “btnContinue” redirects the client to the “Search.aspx” page to find more products to add to the cart.

28

Page 29: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

7. Create a click event handler for the “btnContinue” button and paste the following code:

Response.Redirect("Search.aspx")

8. Create an event handler for btnCheckOut and paste:

' Go to check out pageResponse.Redirect("CheckOut.aspx")

9. Create an event handler for btnLogout and paste:

' Clear all data for this sessionSession.Clear()' Go to login pageResponse.Redirect("Login.aspx")

Coding the Checkout page

The Checkout.aspx page is similar in function to the Cart.aspx page, except that the delete buttons are removes and the user can enter payment information and complete the purchase.

1. Copy the following Imports statements into the code file:

' Import data librariesImports System.Data' Import OLEDB librariesImports System.Data.OleDb' Import special charactersImports Microsoft.VisualBasic.ControlChars

2. Copy the following code into the “Checkout.aspx.vb” file:

' Create DataTable and DateRow objectsDim objDT As System.Data.DataTableDim objDR As System.Data.DataRowDim objDS As System.Data.DataSetDim objDB As New DBConnect

' When page loads either show checkout or invoiceProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

' If the session variable item userID does not exist, login If Session("userID") Is Nothing Then Response.Redirect("Login.aspx")

29

Page 30: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

End If

objDT = CType(Session("Cart"), DataTable)

dgvCart.DataSource = objDT dgvCart.DataBind()

SetTotals()

End Sub

'Public Function GetSubtotal() As Double

Dim intCounter As Integer Dim dblSubtotal As Double

For intCounter = 0 To objDT.Rows.Count - 1 objDR = objDT.Rows(intCounter) dblSubtotal += (CDbl(objDR("Price")) * CDbl(objDR("Quantity"))) Next

Return dblSubtotal

End Function

'Public Function GetTax(ByVal d As Double) As Double

Return d * 0.08

End Function

'Private Sub SetTotals()

Dim dblSubtotal As Double = GetSubtotal() Dim dblTax As Double = GetTax(dblSubtotal)

If objDT.Rows.Count = 0 Then lblSubtotal.Text = "Subtotal: " + (0).ToString("C") lblTax.Text = "Tax: " + (0).ToString("C") lblTotal.Text = "Total: " + (0).ToString("C") Exit Sub End If

lblSubtotal.Text = "Subtotal: " + dblSubtotal.ToString("C") lblTax.Text = "Tax: " + dblTax.ToString("C") lblTotal.Text = "Total: " + (dblSubtotal + dblTax).ToString("C")

End Sub

30

Page 31: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

' This ia a special event handler that detects when one of' the delete buttons in the GridView is clicked.' It uses the index of the clicked button to delete' the peoper row.Protected Sub dgvCart_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles dgvCart.RowDeleting

objDT = CType(Session("Cart"), DataTable) objDT.Rows(e.RowIndex).Delete() Session("Cart") = objDT

dgvCart.DataSource = objDT dgvCart.DataBind()

SetTotals()

End Sub

3. Create a click event handler for the btnPlaceOrder button and paste the following code:

' If the btnPlaceOrder.text is "Place Order" - Place Order' Else go to default pageIf btnPlaceOrder.Text = "Place Order" Then

Dim intCounter As Integer Dim thisTransactionID As Integer Dim thisTransactionDate As String = Now.ToShortDateString

objDT = CType(Session("Cart"), DataTable)

Dim insertTransSql As String = "INSERT INTO tblTransaction" & _ " (fldDate, fldCustomerLoginID, fldIsCredit, fldTax)" & vbCrLf & _ "VALUES (" & vbCrLf & _ "'" & thisTransactionDate & "', " & _ "'" & Session("userID").ToString & "', " & _ 1 & ", " & _ Math.Round(GetTax(GetSubtotal()), 2) & ")" objDB.doUpdate(insertTransSql)

Dim selectTransSql As String = "SELECT MAX(fldID) FROM tblTransaction" objDS = objDB.getDataSet(selectTransSql) thisTransactionID = CInt(objDS.Tables(0).Rows(0).Item(0))

Dim insertCardSql As String = "INSERT INTO tblCredit" & _ " (fldTransactionID, fldNumber, fldType, fldHolder)" & vbCrLf & _ "VALUES (" & vbCrLf & _ thisTransactionID.ToString & ", " & _ "'" & txtCardNumber.Text & "', " & _ "'" & ddlCardType.SelectedItem.Text & "', " & _

31

Page 32: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

"'" & txtCardHolder.Text & "')" objDB.doUpdate(insertCardSql)

Dim insertItemSql As String For intCounter = 0 To objDT.Rows.Count - 1 objDR = objDT.Rows(intCounter) insertItemSql = "INSERT INTO tblLineItem" & _ " (fldID, fldTransactionID, fldUPC, fldPrice, fldQuantity)" & _ vbCrLf & "VALUES (" & vbCrLf & _ intCounter.ToString & ", " & _ thisTransactionID.ToString & ", " & _ "'" & CStr(objDR("UPC")) & "', " & _ CDbl(objDR("Price")) & ", " & _ CInt(objDR("Quantity")) & ")" objDB.doUpdate(insertItemSql) Next

' Thank you message lblMessage.Text = "Thank you for ordering from The Book, CD and " _ " DVD Store" & _ vbCrLf & "Your Invoice Number is: " & thisTransactionID.ToString

lblSubtotal.Visible = False lblTax.Visible = False lblTotal.Visible = False btnEmpty.Visible = False ' Change btnPlaceOrder.text to "Home" btnPlaceOrder.Text = "Home"

Else ' Go to default page Response.Redirect("Default.aspx") ' Clear session data Session.Clear()End If

4. Create a click event handler for the btnEmpty button and paste the following code:

If Not btnPlaceOrder.Text = "Place Order" Then Session.Clear() Response.Redirect("Login.aspx")End If

objDT = CType(Session("Cart"), DataTable)objDT.Clear()

dgvCart.DataSource = objDTdgvCart.DataBind()

SetTotals()

32

Page 33: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

5. Create a click event handler for the btnGoToCart button and paste the following code:

If Not btnPlaceOrder.Text = "Place Order" Then Session.Clear() Response.Redirect("Login.aspx")End If' Got to cart pageResponse.Redirect("Cart.aspx")

6. Create a click event handler for the btnContinue button and paste the following code:

If Not btnPlaceOrder.Text = "Place Order" Then Session.Clear() Response.Redirect("Login.aspx")End If' Go to search pageResponse.Redirect("Search.aspx")

7. Create an event handler for btnLogout and paste:

' Clear all data for this sessionSession.Clear()' Go to default pageResponse.Redirect("Login.aspx")

DBConnect Class

In a separate class named DBConnect paste the following code. This class will provide for all database operations, and can be edited to work for any kind of database. It will also be heavily used in CIS 4342, so make sure you study it and understand what is going on. The Path is static and will have to be changed to the full path on your computer.

Option Explicit On'Option Strict

Imports SystemImports System.DataImports System.Data.OleDb'Imports System.Data.SqlClient'Imports CrystalDecisions.CrystalReports.Engine'Imports CrystalDecisions.Shared

33

Page 34: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Public Class DBConnect

Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _ "Data Source=E:\3309\...\BookCDDVDWeb\App_Data\BookCDDVDShop.mdb" Dim myConnection As New OleDbConnection(connectString) Dim objCmd As OleDbCommand Dim objReader As OleDbDataReader 'Dim SqlConnectString As String = "" 'Dim myConnectionSql As New SqlConnection(SqlConnectString) 'Dim objCmd As SqlCommand 'Dim objReader As SqlDataReader Dim ds As DataSet

Public Sub New() myConnection.Open() 'myConnectionSql.Open() End Sub

Public Function getDataSet(ByVal SqlSelect As String) As DataSet 'InParam is a Select statement. Return is the Dataset 'Note: The Dataset is also stored as a class variable for use 'in the getField function 'Dim myDataAdapter As New SqlDataAdapter(SqlSelect, myConnectionSql) Dim myDataAdapter As New OleDbDataAdapter(SqlSelect, myConnection) Dim myDataSet As New DataSet() myDataAdapter.Fill(myDataSet) ds = myDataSet Return myDataSet End Function

Public Function getDataSet(ByVal SqlSelect As String, ByRef theCount As Integer) _ As DataSet 'InParam is a Select statement, OutParam is the number of rows 'in the returned dataset, Return is a Dataset 'Dim myDataAdapter As New SqlDataAdapter(SqlSelect, myConnectionSql) Dim myDataAdapter As New OleDbDataAdapter(SqlSelect, myConnection) Dim myDataSet As New DataSet myDataAdapter.Fill(myDataSet) ds = myDataSet theCount = ds.Tables(0).Rows.Count() Return myDataSet End Function

Public Function getDataSet(ByVal SqlSelect As String, ByRef theCount As Integer, _ ByRef theErrNum As Integer, ByRef theErrMessage As String) As DataSet 'InParam is a Select statement, OutParams are (1)the number of rows 'in the returned dataset, (2)the error number. If no exception occurs it is zero, 'else it is the error number, (3) the error message if an exception occurs. 'Returns a Dataset Try Dim myDataAdapter As New OleDbDataAdapter(SqlSelect, myConnection) 'Dim myDataAdapter As New SqlDataAdapter(SqlSelect, myConnectionSql) Dim myDataSet As New DataSet

34

Page 35: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

myDataAdapter.Fill(myDataSet) ds = myDataSet theCount = ds.Tables(0).Rows.Count() theErrNum = 0 Return myDataSet Catch e As Exception theErrNum = Err.Number theErrMessage = e.Message Return Nothing End Try End Function

Public Function getDataReader(ByVal SqlSelect As String) As OleDbDataReader 'Public Function getDataReader(ByVal SqlSelect As String) As SqlDataReader 'InParam is a Select statement. Returns DataReader 'objCmd = New SqlCommand(SqlSelect, myConnectionSql) objCmd = New OleDbCommand(SqlSelect, myConnection) Return objCmd.ExecuteReader() End Function

Public Function doUpdate(ByVal SqlManipulate As String) As Integer 'InParam is a SQL manipulate statement (Insert, Update, Delete). 'Returns the number of rows affected by the update. 'If an Exception occurs, -1 is returned 'objCmd = New SqlCommand(SqlManipulate, myConnectionSql) objCmd = New OleDbCommand(SqlManipulate, myConnection) Try Return objCmd.ExecuteNonQuery() Catch e As Exception Return -1 End Try End Function

Public Function doUpdateUsingCmdObj(ByVal aCmdObj As OleDbCommand) As Integer 'Public Function doUpdateUsingCmdObj(ByVal aCmdObj As SqlCommand) As Integer 'InParam is a Command object containing a SQL manipulate 'statement (Insert, Update, Delete). 'Returns the number of rows affected by the update. 'If an Exception occurs, -1 is returned 'This function is used for passing parameters to a Stored Procedure Try 'aCmdObj.Connection = myConnectionSql aCmdObj.Connection = myConnection Return aCmdObj.ExecuteNonQuery() Catch ex As Exception Return -1 End Try End Function

Public Function getDataSetUsingCmdObj(ByVal aCmdObj As OleDbCommand) As DataSet 'Public Function getDataSetUsingCmdObj(ByVal aCmdObj As SqlCommand) As DataSet 'Used for Stored Procedures (Select only) with Parameters aCmdObj.Connection = myConnection

35

Page 36: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

'aCmdObj.Connection = myConnectionSql 'Dim myDataAdapter As New SqlDataAdapter(aCmdObj) Dim myDataAdapter As New OleDbDataAdapter(aCmdObj) Dim myDataSet As New DataSet myDataAdapter.Fill(myDataSet) ds = myDataSet Return myDataSet End Function

Public Function getRow(ByVal ds As DataSet, ByVal row As Integer) As DataRow Dim objRow As DataRow Dim objTable As DataTable = ds.Tables(0) objRow = objTable.Rows(row) Return objRow End Function

Public Function getRows(ByVal Condition As String) As Array 'InParams are (1)a DataSet and (2) the zero based row of the 'table in the DataSet to be returned. Returns a row. Dim objRow() As DataRow Dim objTable As DataTable = ds.Tables(0) objRow = objTable.Select(Condition) Return objRow End Function

Public Function getField(ByVal FieldName As String, ByVal row As Integer) As Object 'InParams are (1)a Field (Column) name as a string and (2)the zero based 'row of the table in the DataSet from which the field is to be extracted. 'Returns the value in the field as a variant type. 'Function assumes that one of the getDataSet functions had been called, 'thus producing a ds at the class level. Dim objRow As DataRow Dim objTable As DataTable = ds.Tables(0) objRow = objTable.Rows(row) Return objRow(FieldName) End Function

Public Sub commitDataSet(ByVal ds As DataSet) 'InParam is a DataSet. This function is used to Commit 'the Dataset to the Data Source when updating a disconnected ds. 'Dim myDataAdapter As New SqlDataAdapter Dim myDataAdapter As New OleDbDataAdapter myDataAdapter.Update(ds) End Sub

Public Function ExecScalarFunction(ByVal aCmdObj As OleDbCommand) As VariantType 'Public Function ExecScalarFunction(ByVal acmdObj As SqlCommand) As VariantType 'InParam is a Command object containing a Select statement 'that returns a single scalar value Variant Type. 'acmdObj.Connection = myConnectionSql aCmdObj.Connection = myConnection Return CType(acmdObj.ExecuteScalar(), VariantType) End Function

36

Page 37: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Public Function getConnection() As OleDbConnection 'Public Function getConnection() As SqlConnection 'NOTE: .NET has implemented its Stored User Defined Functions only 'With the Managed Provider for SQL Server, not the OLEDB provider. 'Return myConnectionSql Return myConnection End Function

Public Sub closeConSql() 'myConnectionSql.Close() myConnection.Close() End Sub

Public Sub resetConnection() myConnection.Close() myConnection.Open() 'myConnectionSql.Close() 'myConnectionSql.Open() End Sub

'Protected Overrides Sub Finalize() ' myConnection.Close() 'End SubEnd Class

Add a personal greeting on all pagesSome Web sites have messages on pages that contain your name. Some examples are:

“Welcome back John Doe!” after a user has successfully logged on.“What can we find for you John?” on the search page.“Would you like another search John?”

After the customer has logged in, create a session variable that contains the customer’s name and place at least three appropriate messages within the Web site.

37

Page 38: cis-iis1.temple.educis-iis1.temple.edu/cis3309/HWA12...  · Web viewActive Server Pages (ASP) is a server-side script-engine technology that combines a Hypertext Markup Language

CIS 3309 – Spring 2012 Book, CD and DVD Sales: ASP.NET 5/5/2023

Run the Web Project

1. Select the Search.aspx page and click the “Start Debugging” button and Internet Explorer should open with the Search.aspx page displayed in the browser.

2. If you receive a message that Web.Config is disabled, choose the option to enable it

.3. When on each page, click the Page button on the tab menu and select View

Source to see the browsers HTML code.

To Submit the Project

There should be two folders associated with the project, one in the Projects folder and one in the Websites folder. The .sln file is in the Projects folder and all the code and data is in the Websites folder. To create a submission folder:

Make a new folder named “yourLastFirstNameWeb” Create new subfolders Projects and Websites Copy the BookCdDvdWeb folders from the Projects and Websites folders to their

respective folders in the “yourLastFirstNameWeb” folder. (Note: If you drag and drop, the files will be moved. To copy the files, hold in the ctrl key before releasing the mouse button.)

Right-click on the folder and Send to Compressed Folder to make a zip file. Submit the zip file.

Additional Tasks

To be more prepared for CIS4342, you should familiarize yourself with “Data Grids” and “Application Variables”. There is information on these topics at various Web sites. Try Google searches to find information and tutorials about them.

The End

38