mypages.valdosta.edu  · web viewblock to this code to build a url with a query string,...

29
Lab 5 – CS 3340 To make this document easier to read, it is recommend that you turn off spell checking and grammar checking in Word: 1. Choose: File, Option, Proofing 2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…” Lab Objectives 1. Understand how postback works 2. Understand how session memory works with one page and across multiple pages 3. Implement page properties using session memory 4. Use a query string to pass information between pages 5. Create a custom class and implement 1-to-many 6. Put an instance of a custom class in session. 7. Bind a list to a DropDownList. Lab Organization There are 10 stages to complete Lab 5. Stag e Description 1 Understanding Postback 2 Understanding Session Memory 3 Using a Page Property Implemented with Session Memory 4 Using Session Memory across Multiple Pages 5 Using a QueryString to Pass Information Between Pages 6a Create & Test Account & AccountManager Classes 6b Develop AccountEntry Form 6c Develop AccountSummary Form 6d Bind AccountManager List to DropDownList 7 Package Assignment for Submission Follow the directions below to complete the lab. 1

Upload: duongtruc

Post on 06-Jul-2019

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

Lab 5 – CS 3340

To make this document easier to read, it is recommend that you turn off spell checking and grammar checking in Word:

1. Choose: File, Option, Proofing2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…”

Lab Objectives

1. Understand how postback works2. Understand how session memory works with one page and across multiple pages3. Implement page properties using session memory 4. Use a query string to pass information between pages5. Create a custom class and implement 1-to-many6. Put an instance of a custom class in session.7. Bind a list to a DropDownList.

Lab Organization

There are 10 stages to complete Lab 5.

Stage Description1 Understanding Postback2 Understanding Session Memory3 Using a Page Property Implemented with Session Memory4 Using Session Memory across Multiple Pages5 Using a QueryString to Pass Information Between Pages6a Create & Test Account & AccountManager Classes6b Develop AccountEntry Form6c Develop AccountSummary Form6d Bind AccountManager List to DropDownList7 Package Assignment for Submission

Follow the directions below to complete the lab.

1

Page 2: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

Stage 1 – Understanding Postback

There is a difference between the “first” time a page is accessed and a postback. Here, we will explore this difference. We will also observe that the contents of controls on a web page are persisted between postbacks.

1. Create your lab05 project (solution folder must be named lab05_lastName).

2. Add a web form named, postback.

3. Add a ListBox and set the ID to lbxNames. Stretch it extra tall.

4. Add a Button beside it and set the ID to btnDisplay

5. Add a TextBox below and set: (a) ID to txtMessage, (b) TextMode to MultiLine and then stretch it larger.

6. Add this code to Page_Load

ListItem li;li = new ListItem("Dave", "11");lbxNames.Items.Add(li);li = new ListItem("Paul", "44");lbxNames.Items.Add(li);li = new ListItem("Anna", "3");lbxNames.Items.Add(li);

7. Run (the button is not active yet)

8. Create an event handler for the button’s click event which displays the text and value of the selected item from the listbox.

9. Run, select a name, press the button. Repeat several times. Note that every time you press the button, the three names are appended onto the existing list in the listbox.

10. (Read, no action required) Why are items added to the listbox every time you press the button?

a. Remember that every time the button is pressed, the page is posted-back to the server where two things occur:

Page_Load is executed, which adds the three names to the listbox btnDisplay_Click is executed

b. Important Point : The values in a control persist between postbacks.

Thus, each time Page_Load executes it adds to the listbox.

2

Page 3: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

c. The page instance can be referenced by this (the same as Java), or with the more common alias, Page. The page class has a property, IsPostBack that returns true if a post-back occurs or false otherwise. To detect whether it is the first time on the page or a postback we can use code like this:

protected void Page_Load(object sender, System.EventArgs e) {if (!Page.IsPostBack) {

// First time on page}else {

// Postback}

}

Thus, to correct this problem, we only want to build the listbox the first time we visit the page, not on postbacks.

11. You fix the problem above so that the page works correctly.

Stage 2 – Understanding Session Memory

You are going to write a page that allows the user to enter a number and press an “Add” button, repeatedly. Each time the button is pressed, the current number is added to the sum of the previous numbers and then the new sum is displayed. To accomplish this, we need to “remember” the previous sum between postbacks. The solution we illustrate is to use session memory.

1. Add a web form named, session1.

2. Add a TextBox and set the ID to txtNum.

3. Add a Button beside it and set the (a) ID to btnAdd, (b) Text to “Add”

4. Add a TextBox below and set: (a) ID to txtMessage, (b) TextMode to MultiLine and stretch it larger.

5. Do the following:

a. Add a click event for the button (double-click the button in Design view).b. Add an instance variable to the page, sum which will hold the sum of the numbers entered.c. Add code to the click event to add the current number to the sum and display the new sum.

public partial class session1 : System.Web.UI.Page {int sum;protected void Page_Load(object sender, EventArgs e) {

}

protected void btnAdd_Click(object sender, EventArgs e) {sum += Convert.ToInt32(txtNum.Text);txtMessage.Text += "Sum=" + sum + "\n";

}}

6. Run, type a number in, Enter, repeat several times. Notice that it does not work correctly.

3

Page 4: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

7. (Read, no action required) Important Points:

a. All instance variables defined in the page are destroyed when the page is sent back to the browser. Thus, the sum is not remembered across postbacks.

b. The internet programming paradigm is stateless, e.g. all variable values are destroyed when the page is sent back to the browser. We can explicitly tell the page to store any variables we want in Session memory. Session is memory that is allocated on the Server which can be used to store information between postbacks. Thus, when the page posts back to the server we can program the page to retrieve any variables we have stored in Session.

c. To put a value in Session, we associate it with a key which we use to retrieve it later. For example, to put a value in Session:

Session.Add("key", value);

And to retrieve it later:

Type value = (Type)Session["key"];

Note that values stored in Session are stored as Objects so we must cast them when we retrieve them.

8. Next, we fix the problem above using session memory. Do the following:

a. Add this code to Page_Load

if(!Page.IsPostBack) {Session.Add("Sum", 0);

}else {

sum = (int)Session["Sum"];}

Note: the first time the page is accessed, we put “Sum” into session, initializing it to 0. On postbacks, we retrieve the value of “Sum” and store it in the instance variable, sum.

b. Add this line to the end of the click event:

Session.Add("Sum", sum);

Important Point: Anytime you change a variable that you want stored in Session you should immediately store it in Session. You will forget to do this and it will haunt you!

c. Run the page and verify that the cumulative sum of the numbers entered is correct.

4

Page 5: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

Stage 3 – Using a Page Property Implemented with Session Memory

We are going to solve the same problem as in Stage 2, except that we will make the code a bit more friendly to read by using an instance variable that is implemented as a C# property that uses session memory.

1. (Read, no action required) In C#, properties are succinct way to define a getter, and a setter for an instance variable in a class. The example below shows how we declare a name instance variable in Java and in C# using a property declaration.

Java C#string name;public string getName() {

return name;}public void setName(string name) {

if (name.Length < 1)this.name =

"unknown";else

this.name = name;}

string name;public string Name {

get { return name; }set {

if (value.Length < 1)name = "unknown";

elsename = value;

}}

Notes: value is a keyword in C# and is used to denote the value being assigned to a property. In C#, the convention is to use an initial capital letter for all public members of a class. By defining a property, we have simplified access. For example, if the property above is defined in a Dog

class, we can write code like this:

Dog dog = new Dog();dog.Name = “Snoopy”;string name = dog.Name;

2. To save a bit of time, we will copy the previous page and give it a new name. This requires several changes, so follow the steps carefully. Do the following:

a. Close session1.aspx and session1.aspx.cs.b. Select session1.aspx in the Solution Explorer and copy it (Ctrl+c)c. Select the project node (lab05) in the Solution Explorer and paste (Ctrl+v)d. The file will be named, session1 – Copy.aspx. Rename it, session2.aspxe. Open session2.aspx in Source view. On the first line, the page directive, and change, the Inherits attribute

from:

Inherits="lab05.session1"

To: Inherits="lab05.session2"

f. Open session2.aspx.cs. Change the name of the class from:

public partial class session1 : System.Web.UI.Page {

5

Page 6: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

To: public partial class session2 : System.Web.UI.Page {

g. Run and verify that the page works correctly. If not, delete session2.aspx and repeat the steps above.

3. Do the following in the code-behind file for session2.aspx:

a. Remove the instance variable:

int sum;

b. Add a Sum property to the page:

public int Sum {get { return (int)Session["Sum"]; }set { Session["Sum"] = value; }

}

Notice that when we set the value of Sum it automatically stores it in session. Similarly, when we request the value of Sum, it automatically retrieves it from session.

c. Delete the code in Page_Load and replace with:

if (!Page.IsPostBack) {Sum = 0;

}

This code is initializing Sum to 0 and storing the result in session the first time the page is accessed. Had we not done this, the first time the click event executed, it would try to retrieve Sum from session before adding the new value, but there would be no value there and the page would bomb.

d. Do the following in the click event handler

i. Remove the last line ii. Change both occurrences of “sum” to “Sum”

The result should look like this:

Sum += Convert.ToInt32(txtNum.Text);txtMessage.Text += "Sum=" + Sum + "\n";

Note that we no longer save the sum in session explicitly. This statement does it implicitly:

Sum += Convert.ToInt32(txtNum.Text);

Look back at the property definition above. When we “set” the Sum this stores the value in session.

4. Run and verify that the page is working correctly.

6

Page 7: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

Stage 4 – Using Session Memory across Multiple Pages

Next, we are going to explore how session memory works across two pages.

1. Do the following:

a. Copy session2.aspx and rename session3a.aspx.b. Make the two changes described in Stage 3, steps 2e & 2f.c. Run the page and verify that it works correctly. If not, delete it and repeat copy.d. Add a button beside the “Add” button and set the (a) ID to btnPage2, (b) Text to “Page 2”e. Add a click event handler for the “Page 2” button and supply this code:

Response.Redirect("session3b.aspx");

When the button is pressed, this code will load the page, session3b.aspx (which we are about to create).

2. Do the following:

a. Copy session2.aspx and rename session3b.aspx.b. Make the two changes described in Stage 3, steps 2e & 2f.c. Run the page and verify that it works correctly. If not, delete it and repeat copy.d. Add a button beside the “Add” button and set the (a) ID to btnPage1, (b) Text to “Page 1”e. Add a click event handler for the “Page 1” button and supply this code:

Response.Redirect("session3a.aspx");

3. Run session3a.aspx and do the following:

a. Type a few numbers in and note the sum.b. Press the “Page 2” button.c. Type a few numbers in and note that it is not adding to the sum from session3a.d. Press the “Page 1” button, type some numbers in. Notice that it started over.

4. (Read, no action required) Session memory works across all pages in an application. In other words, a session variable can be defined in one page and then accessed in another. So why is it not working in this case?

Important Point: Anytime you leave a page (e.g press “Page 2” button) and then return to that page (e.g. press “Page 1” button), IsPostBack is false. In other words when you return to a page, it is the “first time on the page.”

In our example, both pages set the sum to 0 in Page_Load when it is the “first” time on the page:

if (!Page.IsPostBack) {Sum = 0;

}

To fix this problem, we need to only do this when Sum is not found in session. For example, we will add this code:

if (!Page.IsPostBack) {if(Session["Sum"]==null) {

Sum = 0;

7

Page 8: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

}}

5. Remove the code in Page_Load for both pages: session3a.aspx.cs and session3b.aspx.cs and replace with:

if (!Page.IsPostBack) {if (Session["Sum"] == null) {

Sum = 0;}txtMessage.Text = "Current Sum: " + Sum + "\n";

}

6. Run and verify that the sum now carries across the pages.

Stage 5 – Using a QueryString to Pass Information Between Pages

Next, we are going to use a QueryString to pass information between pages.

1. (Read, no action required) Using a QueryString is a technique where you put the information you want to pass to another page in the URL in key/value pairs. The sender writes code like this

Response.Redirect( “newPage.aspx?key1=value1&key2=value2” );

The receiving page writes code like this to retrieve the values:

value1 = Request.QueryString[“key1”];value2 = Request.QueryString[“key2”];

Note that the value is a string, so it will need to be converted if a number is sent.

2. Do the following:

a. Create a new page named, qString1a.aspx.b. Display the page in Source mode.c. Paste the code below inside the div tag . I am providing the code to

display the Gui to save a little time.d. Run the page and it will appear as shown on the right.

<table><tr>

<td><asp:Label ID="Label1" runat="server" Text="First Name"></asp:Label>

</td><td>

<asp:TextBox ID="txtFName" runat="server"></asp:TextBox></td>

</tr><tr>

<td><asp:Label ID="Label2" runat="server" Text="Last Name"></asp:Label>

</td><td>

<asp:TextBox ID="txtLName" runat="server"></asp:TextBox></td>

8

Page 9: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

</tr></table><asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" /><br /><asp:TextBox ID="txtMessage" runat="server" Height="189px" TextMode="MultiLine" Width="304px"></asp:TextBox>

3. Do the following:

a. Create a new page named, qString1b.aspx.b. Display the page in Source mode.c. Paste the code below inside the div tag. d. Run the page and it will appear as shown on the right (a Button and a

multiline textbox)

<asp:Button ID="btnLogOut" runat="server" OnClick="btnLogOut_Click" Text="Log Out" /><br /><asp:TextBox ID="txtMessage" runat="server" Height="172px" TextMode="MultiLine" Width="281px"></asp:TextBox>

4. The Login button on qString1a.aspx will build a query string and use it to pass the first and last names to qString1b.aspx. Do the following:

a. Open qString1a.aspx in Design view.b. Double-click the Login button to create an event handler for the Login buttonc. Paste this code in the event handler.

string fName = txtFName.Text;string lName = txtLName.Text;string url = "qString1b.aspx?fName=" + fName + "&lName=" + lName;Response.Redirect(url);

Now, when you press “Login”, the qString1b.aspx page will displayed and the Url will contain the query string showing the first and last name. Next, we want to retrieve those value into the page.

5. Open the code-behind file for qString1b and paste this code into the Page_Load event handler.

if (Request.QueryString.AllKeys.Contains("fName")) {string fName = Request.QueryString["fName"];string lName = Request.QueryString["lName"];string msg = "Successful Login\n";msg += "First Name=" + fName + ", Last Name:" + lName;txtMessage.Text = msg;

}

9

Page 10: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

6. Run the qString1a.aspx page. Type in names and press Login:

Then, qString1b.aspx is displayed. Note the names contained in the query string for the URL:

7. Next, we program the “Log Out” event handler. When the Log Out button is pressed on the qString1b.aspx page we will redirect to the login page (qString1a.aspx) passing a “status” in the query string indicating that the user has logged out. Then, in Page_Load for qString1a.aspx, we will detect this status and display a message that the user has logged out. Do the following:

a. Open qString1b.aspx in Design view.b. Double-click the Log Out button to create an event handler for the buttonc. In the Log Out event handler, paste this code:

string url = "qString1a.aspx?status=logout";Response.Redirect(url);

d. Open the code-behind file for the qString1a.aspx page.e. In Page_Load, paste this code:

if (Request.QueryString.AllKeys.Contains("status")) {string status = Request.QueryString["status"];if (status.Equals("logout")) {

txtMessage.Text = "You are logged out";}

}

8. Do the following:

a. Run the qString1a.aspx page.

b. Type in names and press Login.

c. Once qString1b.aspx is displayed, press Log Out. You will be returned to qString1a.aspx. Note the “status” in the query string and the message that is displayed

10

Page 11: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

9. (Read, no action required) Suppose a user tries to load qString1b.aspx without logging in. In this case we want to direct them back to the login page (qString1a.aspx). Note the first line of Page_Load in qString1b.aspx:

if (Request.QueryString.AllKeys.Contains("fName")) {

If the URL does not contain a “fName” key, then we will view this as an illegal attempt. Thus, we will add an else block to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this in the login page and display a message.

10. Do the following:

a. Paste this code immediately after the if block in Page_Load for qString1b.aspx:

else {string url = "qString1a.aspx?status=illegalAccess";Response.Redirect(url);

}

b. Paste this code immediately after the inner if block in Page_Load for qString1a.aspx:

else if (status.Equals("illegalAccess")) {txtMessage.Text = "You must login";

}

11. Do the following:

a. Run the qString1b.aspx page.

b. This page will not be displayed, you will be redirected to qString1a.aspx. Note the message and the query string in the URL.

11

Page 12: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

Stage 6a – Create & Test Account & AccountManager Classes

Next, we will create two custom classes and test it. In subsequent stages we will build an application that uses these classes. We will create an Account class to model an account which has an id, name, and balance. Then, we will create an AccountManager class that contains a list of Accounts.

1. (Read, no action required) Classes in C# are similar to Java. We will discuss in more detail in class. Below, we present a few brief notes about classes in C#.

a. As we saw earlier, C# allows a Property construct that encapsulates the getter and setter for an instance variable (field). Below, compare how we do this in C# and Java. Note: By convention, C# uses capitalization for public properties and methods. value is a keyword in C# and represents the value that is being set. We will see an example next.

C# Java// Fieldprivate double balance;

// Propertypublic double Balance { get { return balance; } set { if (value >= 0.0) balance = value; else balance = 0.0; }}

// Fieldprivate double balance;

// Getterpublic double getBalance() { return balance;}

// Setterpublic void setBalance(double balance) { if (balance >= 0.0) this.balance = balance; else this.balance = 0.0;}

b. Compare how we use a class in C# and Java:

C# JavaAccount a = new Account();// Setter, sets the value parameter in the// property definition above to 1000.0a.Balance = 1000.0;// Getterdouble bal = a.Balance;

Account a = new Account();// Settera.setBalance(1000.0);// Getterdouble bal = a.getBalance();

c. As in Java, all classes extend the Object class. As with Java, C# defines a ToString method in the Object class

(note the capitalization of ToString). Note: In C# to override a method we must use the override keyword in the signature. A String in C# is an object. We can use the String class as a reference type; however, it is preferred to

use the alias string.

Compare how we override the ToString method in C# and Java:

C# Javapublic override string ToString() {

return "Bal=" + Balance;}

public String toString() {return "Bal=" + getBalance();

}12

Page 13: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

2. Add Account Class. Do the following:

a. Select lab05 in the SE, right-click and choose: Add, Class (if you don’t see it, choose: Add, New Item, Visual C#, Class)

b. Type the name, Account and press: Add.

c. The Account class should be open. If not, open it. It should look as shown on the left below. Delete the Account class code as shown on the right.

using System;using System.Collections.Generic;using System.Linq;using System.Web;

namespace lab05 {public class Account {}

}

using System;using System.Collections.Generic;using System.Linq;using System.Web;

namespace lab05 {

}

d. Paste the code below inside the namespace block.

public class Account {// Fieldprivate double balance;

// Constructorpublic Account(int id, string name, double balance) {

ID = id;Name = name;Balance = balance;

}// Propertiespublic int ID { get; }public string Name { get; }

public double Balance {get { return balance; }set {

if (value >= 0.0)balance = value;

elsebalance = 0.0;

}}

public override string ToString() {string msg = String.Format("ID:{0}, Name:{1}, Balance:{2:C}", ID, Name,

Balance);return msg;

}}

13

Page 14: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

3. Add AccountManager class. Do the following:

a. Select lab05 in the SE, right-click and choose: Add, Class (if you don’t see it, choose: Add, New Item, Visual C#, Class)

b. Type the name, AccountManager and press: Add.

c. Delete the AccountManager class itself and replace with this code:

public class AccountManager {internal List<Account> accounts = new List<Account>();

public double TotalBalance() {double sum = 0;foreach(Account acct in accounts) {

sum += acct.Balance;}return sum;

}}

d. You will probably have a compile error on the List<Account> accounts line. Add this at the top:

using System.Collections.Generic;

4. Create Account Entry page. Do the following:

a. Add a web form named, AccountEntry.aspx.b. Display the page in Source mode.c. Paste the code below inside the div tag.d. Run the page and it will appear as shown on the right. Yours will not

show “0” beside Num Accounts.e. Open the page in Design view. Double-click all three buttons to

create event handlers. We will supply the code later.

<h2>Account Entry</h2><p>

Num Accounts:<asp:Label ID="lblNumAccounts" runat="server" Text="Label"></asp:Label>

</p><table>

<tr><td>Id</td><td>

<asp:TextBox ID="txtID" runat="server"></asp:TextBox></td>

</tr><tr>

<td>Name</td><td>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>

</tr><tr>

<td>Balance</td>

14

Page 15: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

<td><asp:TextBox ID="txtBalance" runat="server"></asp:TextBox>

</td></tr>

</table><asp:Button ID="btnAddAccount" runat="server" OnClick="btnAddAccount_Click" Text="Add" />&nbsp;<asp:Button ID="btnClearAll" runat="server" Text="Clear All" OnClick="btnClearAll_Click" />&nbsp;<asp:Button ID="btnSummary" runat="server" Text="Summary" OnClick="btnSummary_Click" /><br /><asp:TextBox ID="txtMessage" runat="server" Height="213px" TextMode="MultiLine" Width="344px"></asp:TextBox><br />

5. Next, we will test the Account and AccountManager classes before we actually use them for our application. Do the following:

a. Open the code-behind file for the AccountEntry page and paste this code into Page_Load:

Account a1 = new Account(232, "Rhen", 100.00);Account a2 = new Account(441, "Shay", 200.00);AccountManager acctMan = new AccountManager();acctMan.accounts.Add(a1);acctMan.accounts.Add(a2);txtMessage.Text = "Total Bal:" + acctMan.TotalBalance().ToString("C") + "\n";txtMessage.Text += a1 + "\n";txtMessage.Text += a2 + "\n";

b. Run the page and you should see the output as shown in the figure on the right. If not, delete your files and start this Stage over.

c. Delete the code you just pasted in Page_Load.

Stage 6b – Develop AccountEntry Form

Next, we will develop the AccountEntry form.

1. Create a page property that uses session memory for the AccountManager. Do this by pasting the code below into the AccountEntry code-behind file. Remember, this is a member of the class and thus, should not be inside any method.

public AccountManager AcctMan {get { return (AccountManager)Session["AccountManager"]; }set { Session["AccountManager"] = value; }

}

15

Page 16: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

2. Add the code below to Page_Load.

if (AcctMan == null) {AcctMan = new AccountManager();

}lblNumAccounts.Text = AcctMan.accounts.Count.ToString();

This code does two things:a. If the AccountManager does not exist in session (which it will not the first time the page is loaded), then

create it.b. Update the label with the number of accounts that have been created.

3. Run the page and you should now see that the “Num Accounts” is “0”.

4. Add this code to the btnAddAccount_Click event. Read through the code; you should be able to figure out what is going on

// Build Accountint id = Convert.ToInt32(txtID.Text);string name = txtName.Text;double balance = Convert.ToDouble(txtBalance.Text);Account acct = new Account(id, name, balance);// Add to AccountManagerAcctMan.accounts.Add(acct);// Update LabellblNumAccounts.Text = AcctMan.accounts.Count.ToString();// Display Accountstring msg = "Account added:\n" + acct;txtMessage.Text = msg;// Clear text boxestxtID.Text = null;txtName.Text = null;txtBalance.Text = null;txtID.Focus();

5. Run the page, type data in, and choose, “Add”. Add several more accounts and observe that the “Num Accounts” is properly updated.

6. Add this code to the btnClearAll_Click event. Read through the code; you should be able to figure out what is going on

AcctMan.accounts.Clear();lblNumAccounts.Text = AcctMan.accounts.Count.ToString();txtMessage.Text = null;

7. Run the page, type data in, and choose, “Add”. Add several more accounts. Then, press, “Clear All” and verify that all accounts are removed.

8. Add this code to the btnSummary_Click event. We will create the redirect page next.

Response.Redirect("AccountSummary.aspx");

16

Page 17: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

Stage 6c – Develop AccountSummary Form

Next, we will develop the AccountSummary form.

1. Create Account Entry page. Do the following:

a. Add a web form named, AccountSummary.aspx.b. Display the page in Source mode.c. Paste the code below inside the div tag.d. Run the page and it will appear as shown on the right. Yours will not show

message in the multi-line textbox.e. Open the page in Design view. Double-click both buttons to create event

handlers. We will supply the code later.

<h2>Account Summary</h2><p>

<asp:Button ID="btnAddAccount" runat="server" OnClick="btnAddAccount_Click" Text="Add Account" />&nbsp;

<asp:Button ID="btnStartOver" runat="server" OnClick="btnStartOver_Click" Text="Start Over" /></p><p>

<asp:TextBox ID="txtSummary" runat="server" Height="305px" TextMode="MultiLine" Width="371px"></asp:TextBox></p>

2. Add this method to the code-behind file for AccountSummary.aspx (this is a method, so it doesn’t go inside any other method). Read through the code; you should be able to understand it.

void displayAccounts() {StringBuilder builder = new StringBuilder();

builder.Append("Num accounts : " + AcctMan.accounts.Count + Environment.NewLine);

builder.Append("Total balance: " + AcctMan.TotalBalance().ToString("C") + Environment.NewLine);

builder.Append(Environment.NewLine);

int count = 0;foreach (Account a in AcctMan.accounts) {

count++;builder.Append(count + ". " + a + Environment.NewLine);

}txtSummary.Text = builder.ToString();

}

Note: The reference to the StringBuilder class above will generate a compile error. Add: using System.Text; to the top of your page where the other using statements are.

3. Create a page property that uses session memory for the AccountManager. Do this by pasting this code into the AccountSummary code-behind file:

public AccountManager AcctMan {get { return (AccountManager)Session["AccountManager"]; }set { Session["AccountManager"] = value; }

17

Page 18: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

}

4. Add the code below to Page_Load.

if(!Page.IsPostBack) {if (AcctMan == null) {

txtSummary.Text = "No accounts";}else {

displayAccounts();}

}

5. Run the AccountEntry page, add a few accounts, then choose: “Summary”. You should see a summary of the accounts on AccountSummary.aspx.

6. Add the code below to btnAddAccount_Click event.

7. Add the code below to btnStartOver_Click event. Notice that it clears the session memory and redirects to the AccountEntry page.

Response.Redirect("AccountEntry.aspx");

8. Create a page property that uses session memory for the AccountManager. Do this by pasting this code into the AccountEntry code-behind file:

Session.Clear();Response.Redirect("AccountEntry.aspx");

9. Run AccountEntry and verify that all buttons work correctly on both pages.

Stage 6d – Bind AccountManager List to DropDownList

Next, we will add a drop down on the AccountSummary form and bind to it the list of Accounts contained in the AccountManager, displaying names. When a name is selected, information about the Account will be displayed.

1. On the AccountSummary form:

a. Add a DropDownList beside the “Start Over” button.b. Set the ID to “ddlNames”c. Set AutoPostBack to True.d. Double-click the drop down to create a SelectedIndexChanged event.

2. Add this code to the end of the else block in Page_Load, just below the call to displayAccounts.

ddlNames.DataSource = AcctMan.accounts;ddlNames.DataTextField = "Name";ddlNames.DataValueField = "ID";ddlNames.DataBind();

18

Page 19: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

3. Run the AccountEntry page, add a few accounts then choose, “Summary”. Verify that the names are shown in the drop down. You can select a name, but no action takes place because we have not programmed the event handler yet.

4. Add this code to the ddlNames_SelectedIndexChanged event handler:

int id = Convert.ToInt32(ddlNames.SelectedValue);Account a = AcctMan.accounts.Find(x => x.ID == id);txtSummary.Text = "Account selected:\n" + a.ToString();

5. Run the AccountEntry page and do the following:

a. Add at least two accounts then choose, “Summary”. b. Select a name from the drop down and verify that the associated Account is displayed.c. Choose the “Add Account” button which takes you back to AccountEntry.d. Choose the “Summary” button (no need to add another, but you can)e. Try to select the first name. Note that you have to pick another name below it, then, it will allow you to pick

the first name. We fix this next.

6. Do the following on the AccountSummary page:

a. Add this line to the bottom of the else block in Page_Load:

ddlNames.Items.Insert(0, new ListItem("--Select Name--", "Ignore"));

b. Set the ID to “ddlNames”c. Set AutoPostBack to True.d. Double-click the drop down to create a SelectedIndexChanged event.

7. Run the AccountEntry page and add a few Accounts, choose “Summary”, and verify that the drop down is working as expected.

19

Page 20: mypages.valdosta.edu  · Web viewblock to this code to build a URL with a query string, “status=illegalAccess” and redirect back to the login page. Finally, we will detect this

Stage 7 – Package Assignment for Submission

12. Close VS and zip your lab05_lastName solution folder and submit on Blazeview in the Lab 05 dropbox.

If you need further directions, follow step 11 from Lab 1, exactly, substituting lab05 for lab01.

To avoid a deduction of points verify the following:

i. The name of your zip file is: lab05_lastName (your last name, of course).ii. Inside the zip file, verify that your lab05_lastName solution folder is indeed named: lab05_lastName

iii. Inside your lab05_lastName solution folder there should be:

A lab05.sln file A lab05 folder Some other folders.

20