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

Beginning ASP.NET 2

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

Exercise Answers

Exercise 2

How would you go about adding an image to accompany each news item? Note that it shouldn’t display if there is no news image present for that article.

Solution

Add the following to newsusercontrol.ascx:

<span class=”newsContent”>

<asp:Image style=”float:right” ID=”NewsImage” Runat=”server”

ImageUrl=’<%# Eval(“PictureURL”, “~/NewsImages/{0}”) %>’ /> <%#Eval(“Description”) %>

</span>

Add the following event handler that is called when an item of news is bound:

Sub NewsItem_DataBound(ByVal sender As Object, ByVal e As

System.Web.UI.WebControls.RepeaterItemEventArgs)

Dim row As DataRowView

Dim img As Image

If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType =

ListItemType.AlternatingItem Then

row = CType(e.Item.DataItem, DataRowView)

If row(“PictureUrl”).ToString().Trim() = “” Then

img = CType(e.Item.FindControl(“NewsImage”), Image) img.Visible = False

End If End If

End Sub

Chapter 11

Exercise 1

Create a new user account called Admin, and make this user a member of all of the groups. Log in to the Wrox United site as Admin and test to see whether you can access all of the different pages in both the fan club and the administration section.

Solution

Launch the ASP.NET Web Site Administration Tool and configure the Admin user as shown in Figure A-5.

639

Appendix A

Figure A-5

Exercise 2

Remove the Admin user from any role other than the Administrator role and test the site again. Ensure that you can access the following pages:

Admin.aspx

EditNews.aspx

UpdateProducts.aspx

640

Exercise Answers

Solution

The Admin user account should now have the configuration shown in Figure A-6.

Figure A-6

And if you try to access the Wrox United site, you’ll see the links in Figure A-7 within the Administration section.

641

Appendix A

Figure A-7

Not only can you see these links, but clicking these links will take you to the appropriate pages.

Exercise 3

The Admin user has had a request by a reporter out in the field — he’s uploaded a score for a match, but the score has just changed! Unfortunately, the reporter’s laptop has run out of battery, so he’s asked the Admin to update the score for him. Make sure that the Admin user can update the score of a match.

Solution

You have two options. First, you could add the Admin user to the Reporters role, thereby enabling the access to the page as desired. The alternative is to enable access to the UpdateScore.aspx page on the site to all site Administrators by making the following change to the Web.config file within the root of the Admin folder:

<location path=”UpdateScore.aspx”> <system.web>

<authorization>

<allow roles=”Administrator, Reporter” /> </authorization>

</system.web>

</location>

642

Exercise Answers

Whichever method you decide on, the Admin user needs to be able to access the UpdateScore.aspx page. If you are successful, you will see Figure A-8.

Figure A-8

Exercise 4

Add a field to the user profile for the Wrox United application called DateOfBirth. Give this property a data type of System.DateTime. Add an input field to the FanClub.aspx page so that users can update their date of birth. Note that you will need to convert the value entered in a text box to a DateTime value when you save the data — you might want to try the DateTime.Parse() function for this purpose. To retrieve the data, use the Profile.DateOfBirth.ToShortDateString() function.

Solution

1.First, add the following highlighted line to Web.config:

<profile enabled=”true”> <properties>

<add name=”MemberName”/> <add name=”Name”/>

<add name=”Address”/> <add name=”City”/>

643

Appendix A

<add name=”County”/> <add name=”PostCode”/> <add name=”Country”/>

<add name=”Mailings” type=”System.Boolean”/> <add name=”Email”/>

<add name=”DateOfBirth” type=”System.DateTime”/> <add name=”Theme”/>

<add name=”Cart” serializeAs=”Binary” type=”Wrox.Commerce.ShoppingCart” allowAnonymous=”true”/>

</properties>

</profile>

2.Next, modify FanClub.aspx to include a text box for entering and displaying the date of birth:

<span class=”boxFloat”>Name:<br /> Address:<br />

<br /> <br /> <br />

City:<br /> County:<br /> Postcode:<br /> Country:<br />

Subscribe to email updates:<br /> Email:<br />

Date of Birth: <br /> Membership Alias:<br /> Theme:</span><span>

<asp:TextBox ID=”txtName” runat=”server” Columns=”30” /> <br />

...

<asp:TextBox ID=”txtEmail” runat=”server” /> <br />

<asp:TextBox ID=”txtDoB” runat=”server” />

<br />

<asp:TextBox ID=”txtAlias” runat=”server” /> <br />

...

</span>

3.The code file for the FanClub.aspx page also needs some changes. First, modify the btnSaveChanges_Click event handler code:

Sub btnSaveChanges_Click(ByVal sender As Object, ByVal e As System.EventArgs)

Profile.Name = CType(FCLoginView.FindControl(“txtName”), TextBox).Text

Profile.Address = CType(FCLoginView.FindControl(“txtAddress”), TextBox).Text

Profile.City = CType(FCLoginView.FindControl(“txtCity”), TextBox).Text

Profile.County = CType(FCLoginView.FindControl(“txtCounty”), TextBox).Text

644

Exercise Answers

Profile.PostCode = CType(FCLoginView.FindControl(“txtPostCode”), TextBox).Text Profile.Country = CType(FCLoginView.FindControl(“txtCountry”), TextBox).Text Profile.Mailings = CType(FCLoginView.FindControl(“chkMailing”), CheckBox).Checked Profile.Email = CType(FCLoginView.FindControl(“txtEmail”), TextBox).Text Profile.MemberName = CType(FCLoginView.FindControl(“txtAlias”), TextBox).Text Profile.Theme = CType(FCLoginView.FindControl(“ThemeList”),

DropDownList).SelectedValue

Dim DoB As TextBox = CType(FCLoginView.FindControl(“txtDoB”), TextBox) If DoB.Text <> “” Then

Profile.DateOfBirth = DateTime.Parse(DoB.Text)

End If

Server.Transfer(SiteMap.CurrentNode.Url)

End Sub

Note that you need to check that the text box is not empty (if you try to save with an empty text box, you’ll see an error page due to an exception).

4.Finally, add the following code to the DisplayProfileProperties() method:

Private Sub DisplayProfileProperties()

Dim NameBox As TextBox = CType(FCLoginView.FindControl(“txtName”), TextBox)

If Not (NameBox Is Nothing) Then

CType(FCLoginView.FindControl(“txtName”), TextBox).Text = Profile.Name

CType(FCLoginView.FindControl(“txtAddress”), TextBox).Text = Profile.Address

CType(FCLoginView.FindControl(“txtCity”), TextBox).Text = Profile.City

CType(FCLoginView.FindControl(“txtCounty”), TextBox).Text = Profile.County

CType(FCLoginView.FindControl(“txtPostCode”), TextBox).Text = Profile.PostCode

CType(FCLoginView.FindControl(“txtCountry”), TextBox).Text = Profile.Country

CType(FCLoginView.FindControl(“chkMailing”), CheckBox).Checked = _

Profile.Mailings

CType(FCLoginView.FindControl(“txtEmail”), TextBox).Text = Profile.Email

CType(FCLoginView.FindControl(“txtAlias”), TextBox).Text = Profile.MemberName

CType(FCLoginView.FindControl(“ThemeList”), DropDownList).SelectedValue = _

Profile.Theme

CType(FCLoginView.FindControl(“txtDoB”), TextBox).Text = _

Profile.DateOfBirth.ToShortDateString()

End If

End Sub

This code will convert the DateTime value stored in the user’s profile into its string representation so that it can be displayed on the screen. Because users are unlikely to know the exact time they were born, you can ignore the time part of the date — hence why you’ve used the ToShortDateString() instead of ToString() method. Once finished, you can test it out on the user of your choice. In Figure A-9, I’ve used Alan the Admin.

645

Appendix A

Figure A-9

Chapter 12

Exercise 1

What is the role of SOAP in web services?

Solution

SOAP is a framework for exchanging messages. Its role in web services is to parcel up function calls and parameters to enable you to call the web services remotely in a standardized way.

Exercise 2

Create a web service that retrieves a Wrox United score wherever they’ve scored more than one goal.

646

Exercise Answers

Solution

<WebMethod()> _

Public Function Fixtures() As DataSet

Dim conn As New _ SqlConnection(ConfigurationManager.ConnectionStrings(“WroxUnited”).ConnectionString

)

Dim adapter As New SqlDataAdapter(“SELECT FixtureDate, Opponents, _ FixtureType, GoalsFor, GoalsAgainst FROM Fixtures WHERE GoalsFor>1 ORDER BY _ FixtureDate”, conn)

Dim ds As New DataSet()

adapter.Fill(ds, “Fixtures”)

Return ds

End Function

End Class

Exercise 3

Create a page that consumes the third-party weather forecast for Birmingham, United Kingdom. (Hint: You will also need to discover this service first.)

Solution

Add a Web Reference first via the Add Web Reference function and discover the service by typing the URL www.webservicex.net/globalweather.asmx.

Create a blank page and add a label called Weather Label to it. Then add the following code to the code-behind:

Partial Class WeatherPage

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

Handles Me.Load

Dim wsConvert As New net.webservicex.www.GlobalWeather wsConvert.Credentials = System.Net.CredentialCache.DefaultCredentials

WeatherLabel.Text = wsConvert.GetWeather(“Birmingham”, “United Kingdom”).ToString()

End Sub

End Class

Chapter 13

Exercise 1

The member discount is something that is applied to the shopping cart as you add items to the cart. What do you need to add to the ShoppingCart object to make sure it can store a discount of 10% for fan club members? You can assume that you can detect a fan club member with the property:

HttpContext.Current.User.IsInRole(“FanClubMember”).

Hint: You will need to create a subtotal as well.

647

Appendix A

Solution

You need to create a MemberDiscount property first:

Public Class ShoppingCart

Private Const MemberDiscountPercentage As Single = 0.1

...

Public ReadOnly Property MemberDiscount() As Double Get

If HttpContext.Current.User.IsInRole(“FanClubMember”) Then Return SubTotal * MemberDiscountPercentage

Else

Return 0 End If

End Get End Property

Then you need to create a SubTotal property because between the total and the individual prices of the items, you need to show how you arrive at your figures — otherwise, it will just look like your shopping cart doesn’t add up correctly:

Public ReadOnly Property SubTotal() As Double

Get

Dim t As Double

If _items Is Nothing Then

Return 0

End If

For Each Item As CartItem In _items

t += Item.LineTotal

Next

Return t

End Get

End Property

Then you’ll need in SourceView to add a Panel called DiscountPanel and add two labels, one called SubTotalLabel and another called MemberDiscount and make sure both contain nothing to begin with and that both are visible.

You’ll also need to add some extra parameters to the checkout.aspx page called @subtotal and @memberdiscount and make sure they are added as part of the INSERT clause in this page as well.

Exercise 2

How can you display the member discount details on the Shopping Cart page so that only a fan club member will see them?

Solution

You need to check to see whether a user is in the role FanClubMember and only if they are do you then apply the extra formatting to show the subtotal and the member discount items. Last, you display the discount panel:

648