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

ASP.NET 2.0 Everyday Apps For Dummies (2006)

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

Chapter 12: Ten New Features of ASP.NET 2.0 437

Automatic sorting, which lets the user click a column heading to sort the data.

Updating and deleting. However, you can’t insert a new row using the

GridView control.

Each column in a GridView control is represented by a column that can be bound to a data field. There are actually seven different types of columns you can create:

BoundField: A column bound to a data source field.

ButtonField: A column that contains a button.

CheckBoxField: A column that displays a check box.

CommandField: A column that displays one or more command buttons (command buttons include Select, Edit, and Delete).

HyperLinkField: A column that displays a data source field as a hyperlink.

ImageField: A column that displays an image. The URL for the image is provided by a data source field.

TemplateField: A column that uses a template to specify its contents.

Here’s a GridView control that has five columns. Three of the columns are bound to fields in the data source (catid, name, and desc). The other two columns display command buttons that let the user edit or delete a row, like this:

<asp:GridView ID=”GridView1” runat=”server” AutoGenerateColumns=”False” DataKeyNames=”catid” DataSourceID=”SqlDataSource1” OnRowDeleted=”GridView1_RowDeleted” OnRowUpdated=”GridView1_RowUpdated”> <Columns>

<asp:BoundField DataField=”catid” HeaderText=”ID” ReadOnly=”True”> <HeaderStyle HorizontalAlign=”Left” />

<ItemStyle Width=”80px” /> </asp:BoundField> <asp:BoundField DataField=”name”

HeaderText=”Name”>

<HeaderStyle HorizontalAlign=”Left” /> <ItemStyle Width=”100px” />

</asp:BoundField> <asp:BoundField DataField=”desc”

HeaderText=”Description”> <HeaderStyle HorizontalAlign=”Left” />

438 Part VI: The Part of Tens

<ItemStyle Width=”400px” /> </asp:BoundField> <asp:CommandField

CausesValidation=”False” ShowEditButton=”True” />

<asp:CommandField

CausesValidation=”False” ShowDeleteButton=”True” />

</Columns>

</asp:GridView>

The DetailsView control

The DetailsView control displays one row from a data source at a time by rendering an HTML table. The HTML table contains one row for each field in the data source.

The DetailsView control supports paging, so you can use it to display one row of a data source that returns multiple rows. Then the DetailsView control displays paging controls that let the user navigate through the data.

But a more common way to use the DetailsView control is in combination with a GridView control or other list control that enables the user to select a row. Then the data source for the DetailsView control uses a Select parameter that’s bound to the SelectedValue property of the GridView or other list control. When the user selects a row, the DetailsView control’s data source retrieves the row and the DetailsView control displays the details for that row.

Here’s a typical DetailsView control, adapted from the Product Catalog application that was presented in Chapter 5:

<asp:DetailsView ID=”DetailsView1” runat=”server” AutoGenerateRows=”False” DataKeyNames=”productid” DataSourceID=”SqlDataSource1” > <Fields>

<asp:BoundField DataField=”name” /> <asp:BoundField DataField=”shorttext” /> <asp:BoundField DataField=”longtext” /> <asp:BoundField DataField=”price”

DataFormatString=”<br />{0:c}” /> </Fields>

</asp:DetailsView>

This DetailsView control displays four fields from the data source: name¸ shorttext, longtext, and price. The price field uses a format string to apply a format to the data.

Chapter 12: Ten New Features of ASP.NET 2.0 439

The FormView Control

The FormView control is similar to the DetailsView control. However, instead of rendering data as an HTML table, the FormView control uses templates that let you specify exactly how you want it to render the data. It gives you these template choices:

EmptyItemTemplate: Rendered if the data source is empty.

ItemTemplate: Displays data in read-only mode.

EditItemTemplate: Displayed when the FormView control is in Edit mode.

InsertItemTemplate: Displayed when the FormView control is in Insert mode.

HeaderTemplate: Displayed at the top of the control.

FooterTemplate: Displayed at the bottom of the control.

PagerTemplate: Displayed when paging is enabled.

To display data from the data source, you can use the Eval or Bind methods. For example:

<asp:Label ID=”lblLastName” runat=”server”

Text=’<%# Eval(“lastname”) %>’/>

Here, a label is bound to a data-source field named lastname. Here’s an example that shows how to bind a text box to the lastname field:

<asp:TextBox ID=”txtProductID” runat=”server” Width=”100px”

Text=’<%# Bind(“lastname”) %>’/>

Notice that Bind is used instead of Eval when you want the binding to be two-way — that is, for input as well as output.

You can also include a command button in a template; when the user clicks the button, the specified command is sent to the FormView control. The following commands are allowed:

Edit: Places the FormView control in Edit mode and displays the

EditItemTemplate template.

New: Places the FormView control in Insert mode and uses the

InsertItemTemplate.

Update: Accepts changes made while in Edit mode and updates the data source.

440 Part VI: The Part of Tens

Insert: Inserts a row using data entered while in Insert mode.

Cancel: Cancels Edit or Insert mode and ignores any changes.

For a complete example of a FormView control, refer to the Product Details page presented in Chapter 5.

Login Controls

ASP.NET 2.0 provides an entire set of controls that make it easy to create applications for which users must register and log in. These controls include:

Login: Lets the user log in by entering a user name and password.

CreateUserWizard: Lets the user create a new user account.

PasswordRecovery: Lets the user retrieve a forgotten password.

ChangePassword: Lets the user change his or her password.

LoginView: Displays the contents of a template as appropriate to the user’s login status.

LoginStatus: If the user is logged in, displays a link that logs the user off. If the user isn’t logged in, displays a link that leads to the application’s login page.

LoginName: Displays the user’s login name if the user is logged in.

You’ll find more information about using these controls in Chapters 3 and 4.

The Wizard Control

The Wizard control lets you create wizards that walk the user through a series of steps. Each step can include any content and controls you want it to include. Only one step at a time is displayed, along with navigation buttons that let the user move from step to step.

To define the steps of a Wizard, you use the <WizardSteps> element. This element, in turn, can contain one or more <WizardStep> child elements. There are five different types of steps you can create:

Start: The first step, which includes a Next button but not a Previous button.

Step: An intermediate step, with both a Next and a Previous button.

Chapter 12: Ten New Features of ASP.NET 2.0 441

Finish: The next-to-last step. Instead of a Next button, this step includes a Finish button.

Complete: The final step, displayed after the user clicks the Finish button. No navigation buttons are included on this step.

Auto: The Wizard control determines the step type according to its position in the <WizardSteps> element. For example, the first step declared is the start step.

Here’s a basic skeleton of a simple Wizard control with three steps:

<asp:Wizard id=”Wizard1” runat=”server”> <WizardSteps>

<asp:WizardStep steptype=”Start” title=”Step One”> Content for step one goes here.

</asp:WizardStep>

<asp:WizardStep steptype=”Step” title=”Step Two”> Content for step two goes here.

</asp:WizardStep> <asp:WizardStep steptype=”Finish”

title=”Step Three”>

Content for step three goes here. </asp:WizardStep>

</WizardSteps>

</asp:Wizard>

For more information about using the Wizard control, refer to Chapter 6.

The Generics Feature

Generics is a new language feature introduced with ASP.NET 2.0. It applies to both C# and Visual Basic. The basic idea of the Generics feature is to let you create type-specific classes — particularly, to create strongly typed collection classes that have specified uses.

One of the problems most common to working with collections is that the collections store objects of type Object — that is, a collection can store any type of object. So, if you want to store a collection of Product objects, you might declare an ArrayList and add Product objects to it. Note, however, that nothing prevents you from adding a Customer object to the array list; the Add method of the ArrayList class accepts any object. Result (all too often): mishmash.

With the Generics feature, you can designate the type of object a collection can hold when you declare the collection. For example, you can create an ArrayList that can hold only Product objects. Then the compiler won’t let you add a Customer object to the list.

442 Part VI: The Part of Tens

Other New Features of ASP.NET 2.0

This chapter describes the new ASP.NET 2.0 features that I used in the applications presented in this book. But ASP.NET 2.0 has many other new features as well. Here are a few of the more important ones:

Navigation controls: A set of controls that let you build site-navigation features into your Web applications. These controls include a Menu control for creating menus, a SiteMapPath control that displays a path to the current page, and a TreeView

control that displays the site’s navigation structure as a tree.

WebParts: A set of controls that let you create pages that the user can customize by selecting components called Web parts. The WebParts feature is designed to build portal sites similar to the Microsoft portal, MSN.com.

Themes: A feature that lets you apply formatting to controls and other page elements throughout the application.

The generics features introduces a new namespace (System.Collections. Generic) that provides typed collection classes, including these:

List: A generic array list.

SortedList: A generic list that’s kept in sorted order.

LinkedList: A generic linked list.

Stack: A generic last-in, first-out stack.

Queue: A generic first-in, first-out queue.

Dictionary: A generic collection of key/value pairs.

SortedDictionary: A generic collection of key/value pairs kept in sorted order.

Here’s an example in C# that creates a list of Product objects:

List<Product> plist;

plist = new List<Product>();

Note that you specify the type of object you want contained in a collection by using greater-than (>) and less-than (<) symbols, both when you declare the list and when you instantiate it.

Here it is in Visual Basic, which uses the Of keyword rather than angle brackets:

Dim custlist As List(Of Customer)

custlist = New List(Of Customer)()

Chapter 12: Ten New Features of ASP.NET 2.0 443

The Web Site Administration Tool

ASP.NET 2.0 includes a new feature called the Web Site Administration Tool that lets you configure web.config settings from a browser-based interface. You can also create the user accounts used by the new Login controls. To use this tool, choose the Web Site ASP.NET Configuration command from within Visual Studio. Note that this tool works only for file system Web sites, which means you probably won’t be able to use it for applications that have been deployed to an IIS server and are in production. Figure 12-3 shows the opening page of the Web Site Administration Tool.

Figure 12-3:

The Web

Site

Administrati

on Tool.

444 Part VI: The Part of Tens

Chapter 13

Ten Rookie Mistakes

In This Chapter

Coding too soon

Skimping on documentation

Inadequate testing

Abusing state features

Not validating input data

Reinventing the wheel

Not asking for help

If you’re relatively new to programming in general or ASP.NET Web programming in particular, this chapter is for you. It forewarns you about

some of the most common mistakes made by inexperienced developers. Human nature being what it is, experienced developers make these mistakes too; most of them are caused by our desire to get on with the nitty-gritty of programming rather than getting stuck in the more tedious — but vital — aspects of development, such as planning, testing, and documenting our code.

Coding Too Soon

Probably the most common application development mistake is to start coding too soon. This is a natural mistake to make, since programming is what programmers do. But you should resist the temptation to begin writing code for your application until you’ve thoroughly designed the application and thought through how you will handle the more challenging aspects of the code. In particular, you should make sure your application design addresses the following issues:

How will database access be handled? Will you use ASP.NET data source controls such as SqlDataSource to handle data access declaratively, or will you write custom data access classes? Will you include SQL statements in your code, or will you use stored procedures to store the SQL statements in the database?

446 Part VI: The Part of Tens

How will you pass state information from page to page? Will you rely on ASP.NET’s session-state feature, or will you pass query strings around among the application’s pages?

How will you protect the application from security breaches? In what ways will the application be vulnerable to attacks such as SQL injections, and how can you design the application to protect itself from such attacks?

How will the application handle error situations? For example, how do you want it to respond to database-connection problems?

Don’t start coding your application until you’ve resolved these issues.

For more complicated applications, it’s sometimes a good idea to do a simple version of the application before you write the complete application, just to make sure the application can be done. This proof-of-concept version should focus on the most troublesome parts of the application, such as linkages to other existing applications or tricky database design issues. Once you’ve established that the application is doable, you’ll have the knowledge and confidence you need to prepare a detailed application design.

Skimping On Documentation

Most developers love good documentation in other people’s programs, but they hate doing it because it’s tedious work. And it involves writing. (I happen to like to write, but I realize that I’m a bit weird. Most people don’t like to write.)

Another reason most developers hate documentation is that it doesn’t seem productive. Why waste the day writing about what you did yesterday, when you could be writing more code?

The answer is that today you probably remember what you did yesterday and why you did it. But six months from now, you won’t. So even if you hate doing the documentation, suffer through it; your future self will be glad you did.

Remember that there are two basic kinds of documentation you should prepare. First, you should liberally sprinkle your code with inline comments that explain what’s going on. And second, you should prepare separate documents that explain what the application does, how it is designed, and how to use the application.