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

Beginning ASP.NET 2

.0.pdf
Скачиваний:
23
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Exercise Answers

<tr>

<td style=”width: 150px”> Chris Hart</td>

<td style=”width: 400px”> Signed my book!</td>

</tr>

<tr>

<td style=”width: 150px”>

Chris Ullman</td>

<td style=”width: 400px”> Signed my football!</td>

</tr>

</table>

</form>

</body>

</html>

Exercise 2

Head back to Wrox United and go to the Master page. Try deleting the Menu control and replacing it with a TreeView control. Bind that control to the siteData data source, and bingo — you should see a fully populated tree of items, both in Design View (refer to Figure 3-45) and when you run the page (refer to Figure 3-43).

Solution

Changing the Menu control to a TreeView control is a swift process, and you can see the results in Figure A-2.

Figure A-2

Once you have a siteMap data source, it’s simple to plug in compatible controls and change the functionality of the site with minimal effort.

629

Appendix A

Chapter 4

Exercise 1

Change the configuration of your Chapter 4 web site to allow anonymous access, but to deny access to one specific user account.

Solution

Run through the Security wizard for the site and change the permissions as described, or modify the Web.config file. If you are successful, you will have code similar to the following in your Web.config file:

<roleManager enabled=”true” /> <authorization>

<allow users=”?” />

<deny users=”chrishart” /> </authorization>

Exercise 2

Add a subfolder to the Chapter 4 web site called Admin. Within this folder, add a page called MainAdmin.aspx with a LoginName control on it and any other controls you might want. Change the access permissions for that specific folder so that only members of the Administrators group can view the page.

Solution

The MainAdmin.aspx page should have code similar to the following:

<form id=”form1” runat=”server”> <div>

This is the administration page for the Chapter 4 site. <br />

<asp:LoginView ID=”LoginView1” Runat=”server”> <LoggedInTemplate>

You are logged in as <asp:LoginName ID=”LoginName1” Runat=”server” />  <br />

</LoggedInTemplate>

<AnonymousTemplate>

You are currently anonymous. </AnonymousTemplate>

</asp:LoginView>

<asp:LoginStatus ID=”LoginStatus1” Runat=”server” /> </div>

</form>

And the Web.config file for the Admin folder should have the following code:

<?xml version=”1.0” encoding=”utf-8”?> <configuration>

<system.web>

<authorization>

<allow roles=”administrators” />

630

Exercise Answers

<deny users=”*” /> </authorization>

</system.web>

</configuration>

Chapter 5

Exercise 1

You have an ASP.NET Label control on a page. The label has a font-italic=”true” attribute, and a

CssClass=”maintext” attribute:

<asp:label id=”myLabel” CssClass=”maintext” font-italic=”true”

text=”This is a label”></asp:label>

The page has an associated CSS style sheet (not associated with a theme) that defines a .maintext style class has the following attributes:

.maintext

{

color: Navy; font-family: Verdana; font-weight: Bold; font-style: normal;

}

How will the label appear when it is rendered?

Solution

You should see some text rendered in bold, blue Verdana, and in italic, as shown in Figure A-3.

Figure A-3

The font-style attribute in the CSS style sheet is overridden by the element-specific style in the page.

631

Appendix A

Exercise 2

You now add a Theme=”ExerciseTheme” to the preceding page. You place the CSS style sheet from the previous exercise within the ExerciseTheme theme folder. How will the label control appear now?

Solution

The Theme attribute specifies that the page should now inherit all styles within the ExerciseTheme theme folder, but the style attribute added to the element remains, and the font appears in italic.

Exercise 3

You define a skin for all labels within the ExerciseTheme theme folder and specify the following attributes:

<asp:Label CssClass=”maintext” runat=”server” font-italic=”false”></asp:Label>

How will the label appear now?

Solution

This time around, the Label control’s italic style will override the page’s style, so you will see what appears in Figure A-4.

Figure A-4

Chapter 6

Exercise 1

In the Chapter06 project create a new Web Form called Lists.aspx and add a ListBox control to the page, and add three list items with values of One, Two, and Three. Add a Label control and a Button control to the page. In the Click event of the Button, display the selected value of the ListBox in the

Label.

Solution

The controls you add to the page should be:

632

Exercise Answers

<asp:ListBox ID=”ListBox1” runat=”server”> <asp:ListItem Text=”One” /> <asp:ListItem Text=”Two” /> <asp:ListItem Text=”Two” />

</asp:ListBox> <br />

<asp:Button ID=”Button1” runat=”server” Text=”Button” /> <asp:Label ID=”Label1” runat=”server” Text=”Label” />

For the Click event of the button you should have:

Protected Sub Button1_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handlers Butto1.Click

Label1.Text = ListBox1.SelectedValue

End Sub

This event procedure relies on the fact that there is a property on the ListBox that identifies what the value is for the selected item — the SelectedValue property. In fact there is also a SelectedText value, because a ListBox has both a Text and a Value property; the Text is what’s displayed, whereas the Value is stored in the page and not shown to the user. This is useful for values that come from a database, where the Value would be the ID of the item and the Text would be the description. The same is true for a DropDownList control.

Exercise 2

Modify Exercise 1 so that just selecting an item in the list posts back to the server (meaning you don’t need to click the button). You’ll need to add an event procedure to the ListBox, and in that event procedure you can use the same code from the Click event of the Button to display the selected value in the Label. Hint: The terms postback and automatic might be useful in your hunt for correct properties.

Solution

To allow the ListBox to post back automatically, you set the AutoPostBack property to True. Now when a list item is selected, the postback will happen right away, rather than waiting for a button to be clicked. On its own, this just posts back, so you also need an event procedure for the ListBox, and for this you use the SelectedIndexChanged event, which is raised when the selected item changes. The event is only raised when the selected item changes, so repeated clicking of the same item will not cause unnecessary postbacks. The event procedure should be

Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, _

ByVal e As System.EventArgs) Handlers ListBox1.SelectedIndexChanged

Label1.Text = ListBox1.SelectedValue

End Sub

The advantage of this event over a postback from a button event is that you can have your page change depending upon the user selection. For example, you could have a grid filter the data shown depending on the value in a list box.

Exercise 3

Modify the EditSquad.aspx example so that the GridView is refreshed when a new player is added to the squad. The technique is similar to the code you already have, but you’ll need to use a different event. Remember that you can use the drop-down lists in the code view to find the events.

633

Appendix A

Solution

To refresh the GridView when a new player is added to the squad, you need to use the Inserted event. Just as when the data for a SqlDataSource control is updated, the Updated event is raised, when a new row is inserted, the Inserted event is raised. You can create this in exactly the same way as you did for the Updated event, and use the same code in the event procedure.

The code for the Inserted event procedure is

Protected Sub DetailsDataSource_Updated(ByVal sender As Object, _

ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) _ Handles DetailsDataSource.Inserted

GridView1.DataBind End Sub

Chapter 7

Exercise 1

Describe the general capabilities of data source and data-bound controls.

Solution

Data source controls connect to the source of data and enable communicating to the database the information for behaviors such as reading, editing, and deleting.

Data-bound controls render spaces on the page that interact with the user, either to display values or to accept input for changes to the data.

Exercise 2

Which data-bound controls render data in tables?

Solution

GridView (one datum in each cell), DataList, and Repeater (all fields of one record in each cell).

Exercise 3

Compare and contrast the DetailsView and FormView controls.

Solution

Both present data in a tabular form with only one record displayed at a time. Both support reading and changing values, as well as creating and deleting entire records. The DetailsView control has a built-in default template, whereas FormView has no default template.

Exercise 4

Describe how a GridView control can limit its records to only those that match a player’s name selected in a DropDownList of last names.

634

Exercise Answers

Solution

The DropDownList control displays names in its Text property, and also holds the player’s ID number in the Value property. The GridView control has a SelectCommand that contains a WHERE clause that sets the ID equal to a parameter (prefaced by the @ sign). The GridView control also has a parameter tab containing a parameter that is filled with the value of the selected item of the DropDownList. Set AutoPostBack to TRUE in the DropDownList box so the following behavior is automatic. When a user changes a selection in the DropDownList, ASP.NET 2.0 automatically places the value of that selection into the GridView control’s parameter tag, which means it will be employed in the SelectCommand WHERE clause. ASP.NET 2.0 will then cause the GridView control to create a new request for data using the new SelectCommand. The data returned will only have records that match the ID of the player selected in the DropDownList.

Exercise 5

Which data source control is best suited for the Menu or SiteMapPath data-bound controls?

Solution

The SiteMapDataSource is best suited because it is optimized to read the XML file holding the site description information.

Chapter 8

Exercise 1

Enabling the capability to write to a database requires changes to the properties of a data source control, a data-bound control, or both?

Solution

Both.

Exercise 2

Describe the difference between an asp:Parameter and an asp:ControlParameter.

Solution

An asp:Parameter holds the value that came from the record of the database. An asp:ControlParameter holds a value that was entered by the user into a control.

Exercise 3

What problem does the DataKeyNames property solve?

Solution

Some fields hold values that uniquely identify them among all the records. When a user changes values in those fields there is a conundrum in that ASP.NET 2.0 needs the old values in order to find the record and the new values for the writing. DataKeyNames are those fields for which ASP.NET 2.0 will hold both original and new values. When an update is made and a change is made to an ID field, ASP.NET 2.0 uses

635

Appendix A

the new value for the SET part of the command (which writes) and the old value for the WHERE part of the command (which finds the one record to change).

Exercise 4

A page needs to delete the date of birth value from one record. Which command should be used?

Solution

Update. Delete would only be used to eliminate the entire record, not just one value in the record.

Exercise 5

What tags must be added to a page to allow a GridView to create new records?

Solution

This is a trick question because a GridView cannot perform inserts. But the GridView can have a button that opens a DetailsView in Insert mode, which can create a new record.

Chapter 9

Exercise 1

Create a class and shared method (called DeliveryDate) to calculate delivery date given the date of an order. All deliveries should be made within three days of the order.

Solution

Public Class Orders

Public Shared Function DeliveryDate(OrderDate As DateTime) As DateTime

Return OrderDate.AddDays(3)

End Function

End Class

This simply uses the AddDays method of the DateTime data type to add the required number of days.

Exercise 2

Continuing from Exercise 1, modify the DeliveryDate method to take into account that deliveries do not happen on the weekend.

Solution

Public Class Orders

Public Shared Function DeliveryDate(OrderDate As DateTime) As DateTime

Dim deliveryDay As DateTime = OrderDate.AddDays(3)

If deliveryDate.DayOfWeek = DayOfWeek.Saturday Then deliveryDate = deliveryDate.AddDays(2)

ElseIf deliveryDate.DayOfWeek = DayOfWeek.Sunday Then deliveryDate = deliveryDate.AddDays(2)

636

Exercise Answers

End If

Return deliveryDay

End Function

End Class

Here the delivery date is calculated and checked to see if it falls on a Saturday or Sunday, in which case the delivery date is moved to the following Monday.

Exercise 3

Modify the DeliveryDate method to take into account that an order takes three working days to process. So orders falling on a Thursday will be delivered on the following Monday, and orders from Friday will be delivered on the following Tuesday.

Solution

Public Class Orders

Public Shared Function DeliveryDate(OrderDate As DateTime) As DateTime

Select Case OrderDate.DayOfWeek

Case DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday

Return OrderDate.AddDays(3)

Case DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday

Return OrderDate.AddDays(5)

Case DayOfWeek.Sunday

Return OrderDate.AddDays(4)

End Select

End Function

End Class

This version of the method uses the Select Case statement to calculate different dates depending on the day of week on which the order was placed.

Exercise 4

For each of the following Boolean expressions, say for what integer values of A each of them will evaluate to True and when they will evaluate to False:

a.

b.

c.

d.

e.

NOT A=0

A > 0 OR A < 5

NOT A > 0 OR A < 5

A > 1 AND A < 5 OR A > 7 AND A < 10

A < 10 OR A > 12 AND NOT A > 20

637

Appendix A

Solution

a. True for all integers except zero. Without the NOT, the answer would only be zero. When you add the NOT, it reverses to be all numbers except zero.

b. True for all integers. The left side alone would be True for all integers greater than zero (only zero and negative integers would be false). The right side includes all integers that are less than 5, including zero and negative integers. With the OR clause an integer has to be within one of the two expressions in order for the entire expression to be True. When you combine these two sets of answers you get all integers. (The integers 1 through 4 are included by both expressions.)

c. True for integers 5 and below. Integers 6 and above will evaluate to False. The issue here is precedence between the NOT and OR operators. The NOT is only applied to the expression on the left of the OR. Think of this problem as (NOT A > 0) OR (A < 5). On the left you have True for any numbers that are not greater than zero, so True is for zero and negative numbers. On the right you have True for any number that is less than 5. With the two sides of the OR combined, you have True for all negative numbers and zero and positive numbers up to 5. Numbers greater than and including 6 are True for either side and thus resolve to False.

d. True for 2, 3, 4, 8, and 9 only. Like the previous problem, the issue is to establish the precedence of the operators. Think of this as (A > 1 AND A < 5) OR (A > 7 AND A < 10). On the left of the OR you can see that only integers 2, 3, and 4 would fit both criteria. On the right side of the OR the situation is similar; only 8 and 9 meet both criteria. When you consider the OR you have to combine those two answer sets.

e. True for all integers 9 and below (including zero and negatives) and for 13 through 20 inclusive. False for 10, 11, 12, and all integers above (and inclusive of) 21. Think of this problem with some parentheses. The OR is the last to be evaluated, so your parentheses are (A < 10) OR (A > 12 AND NOT A > 20). First look at the right side of the OR. Integers must meet both tests when there is an AND clause, so that would be 13 through 20 are True. Now look at the left side of the OR. Any number less than 10 will be True. The final answer is the combination of those two answer sets.

Chapter 10

Exercise 1

Create a new web site and a new page called CodeBehind.aspx with a single label, but making sure that you don’t check the box marked Placed Code in a Separate File. Now create a code-behind file manually for that page that displays the content of the label.

Solution

Create a class called CodeBehind.cs. Add the following line of code to the CodeBehind.aspx:

<@Page CodeFile=”CodeBehind.cs” Class=”CodeBehind” %>

In the CodeBehind.aspx file, add the following within the Page_Load event:

Label1.Text = “Hello World”

638