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

ASP.NET 2.0 Everyday Apps For Dummies (2006)

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

Chapter 13: Ten Rookie Mistakes 447

Inadequate Testing

The most common mistake when testing a computer program is to assume that the purpose of testing is to make sure your program works. That’s exactly the opposite of the approach you should take. Instead of trying to prove your program right, you should try to prove it wrong. Do everything you can think of to make your program fail.

Always keep in mind the many ways your users will use and abuse your program. Here are just a few crazy things to try when you’re testing your applications:

Try leaving all the input fields blank.

Try entering data that includes angle brackets < >.

After you type data into a data-entry page, hit the browser’s Back button to return to the data-entry page — and enter the same data again.

After you delete or update a record, hit the browser’s Back button, then try to delete or update the same record again.

Have someone who has never seen the application before test the application. We developers tend to get into a rut when we test our applications, testing the same things over and over again. You’ll be surprised at the errors discovered by someone who has never before seen the application.

Also, remember the principle of regression testing: Whenever you make any change to the application, you need to retest the entire application, not just the part you change. You never know what unintended consequences the change may have.

Abusing State Features

ASP.NET provides several convenient ways to save state information, including session state and view state. However, it’s easy to overuse these features. Here are some ways you can improve the way your application works with state features:

Disable view state for controls that don’t need it. By default, most ASP.NET controls enable view state. This needlessly sends state information to the browser for each page. The application will run more efficiently if you use view state only when necessary.

448 Part VI: The Part of Tens

Try not to save excessive amounts of data in session state. Session state is usually stored in server RAM, which is a precious resource shared by all users of the application.

Remove data from session state as soon as you know you won’t need it any more.

Not Validating Input Data

All data allowed into an application should be validated. ASP.NET includes a rich set of validation controls, and you should rarely code a text box or other input control without at least one validation control to go along with it. At minimum, a text box should include a RequiredFieldValidator if it gathers required data; text boxes that gather numeric data should use validators to ensure that the data is of the correct type (and, if appropriate, within the correct range).

One common omission is to forget to check for negative numbers for values that must be positive. For example, a quantity field in a shopping cart application shouldn’t allow negative values.

Another common mistake is to forget to treat query strings as input data. ASP.NET lets you use validation controls to automatically validate input data received from text boxes and other input controls. However, query strings are a form of input data too, but ASP.NET doesn’t provide an automatic way to validate them. So you have to write code that manually validates query string fields before your program uses those values. If you don’t, malicious users can alter or fake query string values in an attempt to hack your application. A word to the wise: Never assume that a query string contains valid or legitimate data.

Reinventing the Wheel

I recently needed to write a routine that would sort the letters of a word into alphabetical order. I was working in C, not C# or Visual Basic, so I had no sort function or method available. Rather than work out the details of how to write a sort routine from scratch, I just grabbed a book off my shelf, looked up sort in the index, found a good routine, and shamelessly copied it into my program.

Chapter 13: Ten Rookie Mistakes 449

Before you spend hours, days, or weeks writing code, find out if the code you’re developing is already available. Odds are it is.

In fact, you should apply this principal to the entire application. You may find that you can purchase a ready-made application that does exactly — or almost exactly — what your application will do. Depending on the purchase price, of course, it may be considerably less expensive to buy the ready-made solution.

Not Asking for Help

There are plenty of places on the Internet where you can ask for help and get good (and sometimes useful) answers. One of the best-known (and best) is the forums section of www.asp.net. There you can post a question and get answers, usually within a few hours or a day. It always amazes me that other ASP.NET programmers are so often willing to help others with programming problems.

Of course, you shouldn’t abuse the willingness of others to help. Don’t post questions before you’ve spent a reasonable amount of time researching the answer yourself and trying several different solutions. In particular, be sure to read whatever the online help has to say about the controls and classes you’re having trouble with.

Before you post, search the forum for similar questions. You may well find that someone has already asked your question and the answer to your problem is there, waiting for you to read it.

450 Part VI: The Part of Tens

Chapter 14

Ten Database Design Tips

In This Chapter

Using the right number of tables

Avoiding repetition of data

Avoiding redundant data

Using a naming convention

Avoiding nulls

Avoiding secret codes

Using constraints wisely

Using triggers when appropriate

Using stored procedures

One of the most important aspects of any application-development project is the database design. And so, without further ado, here are ten-or-

so tips for designing good databases, straight from the Home Office in sunny Fresno, California.

Use the Right Number of Tables

In Amadeus (one of my all-time favorite flicks from the ’80s), the Emperor of Germany criticizes one of Mozart’s works as having “too many notes.” Mozart replies indignantly that he uses neither too many nor too few notes, but the exact number of notes that the composition requires.

So it should be with database design. Your database should have as many tables as the application requires — not more, not fewer. There is no single “right” number of tables for all databases.

Inexperienced database designers have a tendency to use too few tables — sometimes trying to cram an entire database-worth of information into a single table. At the other extreme are databases with dozens of tables, each consisting of just a few fields.

452 Part VI: The Part of Tens

Avoid Repeating Data

One of the core principles of relational database design is to handle repeating data by breaking it out into a separate table. For example, in the old days of flat-file processing, it was common to create invoice records that had room for a certain number of line items. Thus the invoice record would have fields with names like Item1, Item2, Item3, and so on.

Bad!

Whenever you find yourself numbering field names like that, you should create a separate table. In the case of the invoice record, you should create a separate table to store the line item data.

Avoid Redundant Data

When designing the tables that make up your database, try to avoid creating redundant data. Whenever redundant data creeps into a database, it introduces the likelihood that the data will become corrupt. For example, suppose you store a customer’s name in two different tables. Then, if you update the name in one of the tables but not the other, the database has become inconsistent.

The most obvious type of redundant-data mistake is to create a field that exists in two or more tables. But there are more subtle types of redundant data. For example, consider an Invoice table that contains a LineItemTotal field that represents the sum of the Total fields in each of the invoice’s line items. Technically, this field represents redundant data; the data is also stored in the Total fields of each line item.

Whether you should allow this type of redundancy depends on the application. In many cases, it’s better to put up with the redundancy for the convenience and efficiency of not having to recalculate the total each time the data is accessed. But it’s always worth considering whether the added convenience is worth the risk of corrupting the data.

Use a Naming Convention

To avoid confusion, pick a naming convention for your database objects and stick to it. That way your database tables, columns, constraints, and other objects will be named in a consistent and predictable way. (Just think of the savings on aspirin.)

Chapter 14: Ten Database Design Tips 453

You can argue from now until St. Swithen’s day about what the naming conventions should be. That doesn’t matter so much. What does matter is that you make a convention — and follow it.

Avoid nulls

Allowing nulls in your database tables significantly complicates the application programming required to access the tables. As a result, I suggest you avoid nulls by specifying NOT NULL whenever you can. Use nulls rarely, and only when you truly need them.

Nulls are often misused anyway. The correct use of null is for a value that is unknown; not for a blank or empty value. For example, consider a typical address record that allows two address lines, named Address1 and Address2. Most addresses have only one address, so the second address line is blank. The value of this second address line is, in fact, known — it’s blank. That’s not the same thing as null. Null would imply that the address may have a second address line; we just don’t know what it is.

Even for columns that might seem appropriate for nulls, it’s usually more convenient to just leave the column value blank for values that aren’t known. For example, consider a phone number column in a Customer table. It’s safe to assume that all your customers have phone numbers, so it would be correct to use null for phone numbers that you don’t know. However, from a practical point of view, it’s just as easy to disallow nulls for the phone number column, and leave the unknown phone numbers blank.

Avoid Secret Codes

Avoid fields with names like CustomerType, where the value of the field is one of several constants that aren’t defined elsewhere in the database, such as R for Retail or W for Wholesale. You may have only these two types of customers today, but the needs of the application may change in the future, requiring a third customer type.

An alternative would be to create a separate table of customer-type codes (call it CustomerTypes), and then create a foreign-key constraint so the value of the CustomerType column must appear in the CustomerTypes table.

454 Part VI: The Part of Tens

Use Constraints Wisely

Constraints let you prevent changes to the database that violate the internal consistency of your data. For example, a check constraint lets you validate only data that meets certain criteria. For example, you can use a check constraint to make sure the value of a field named Price is greater than zero.

A foreign-key constraint requires that the value of a column in one table must match the value that exists in some other table. For example, if you have a LineItems table with a column named ProductID, and a Products table with a column also named ProductID, you could use a foreign-key constraint to make sure that the ProductID value for each row in the LineItems table matches an existing row in the Products table.

Use Triggers When Appropriate

A trigger is a procedure that kicks in when certain database data is updated or accessed. Triggers are a great way to enforce those database rules that are more complicated than simple constraints. For example, suppose an Invoice table contains an ItemCount column whose value is the number of line items for the invoice. One way to maintain the value of this column automatically would be to create triggers that increment the ItemCount column whenever a line item is inserted, and decrement the ItemCount column whenever a line item is deleted. Sometimes automation is a beautiful thing.

Use Stored Procedures

Stored procedures are SQL procedures that are tucked away in the database and are part of it. There are several advantages to using stored procedures instead of coding SQL in your applications:

Using stored procedures removes the burden of SQL programming from your application programmers. Instead, it makes the SQL used to access the database a part of the database itself — no fuss, no muss. All the application programs have to do is call the appropriate stored procedures to select, insert, update, or delete database data.

Stored procedures are more efficient as a way of handling transactions, because the database server handles the entire transaction.

Stored procedures are also more efficient because they reduce the amount of network traffic between the database server and the Web server.

Finally, stored procedures are more secure because they reduce the risk of SQL injection attacks.

Appendix

About the CD

Iincluded a CD to provide you with all the source code for the applications presented in this book. That way you won’t have to type everything in

from scratch. In this appendix, I explain the requirements for using the CD — and show you how to install and use the applications.

System Requirements

Basically, any modern PC will be sufficient to run the applications on this CD, provided the computer is powerful enough to run Visual Studio 2005 or Visual Web Developer 2005 Express Edition. Here’s what you need at minimum:

A PC with a Pentium processor, running at 600MHz or faster. (The faster the better, of course.)

128MB of RAM.

Windows XP with Service Pack 2. Or, Windows 2003 Server or Windows 2000 Service Pack 4.

At least 1.3 GB of space available on your hard drive. (That’s to install Visual Web Developer 2005 Express Edition. The applications on the CD don’t require nearly that much disk space.)

A monitor that can display at least 800x600 pixels in 256 colors.

A mouse or other pointing device.

A CD-ROM drive.

Any way your system can exceed these requirements is, by and large, all to the good — and the more it exceeds them, the better.

456 ASP.NET 2.0 Everyday Apps For Dummies

Using the CD

To install the applications on the CD, follow these steps:

1.Insert the CD into your CD-ROM drive.

The license agreement should automatically appear. Note that if you have disabled the AutoRun feature in Windows, you’ll have to start the installation program manually. To do so, choose Start Run, and then enter d:\start.exe. (Replace d: with the proper drive letter if your CD drive isn’t drive d.)

2.Read the license agreement, and then click the Accept button to access the CD.

The CD interface appears, which allows you to install the applications.

Using the Source Files

The CD contains the source files for all applications presented in this book. Both the C# and Visual Basic versions are included. You can copy any or all of these applications to your hard drive, and then access them from Visual Studio 2005 or Visual Web Developer 2005 Express Edition as file-system applications. Note that the installation program will let you chose to copy just the C# or VB versions of the applications if you want.

Here is the folder structure for the applications:

Apps\LoginCS

Apps\LoginVB

Apps\CatalogCS

Apps\CatalogVB

Apps\CartCS

Apps\CartVB

Apps\MaintCS

Apps\MaintVB

Apps\OrderListingCS

Apps\OrderListingVB

Apps\ContentCS

Apps\ContentVB