Beginning ASP.NET 2.0 E-Commerce in C# 2005 From Novice to Professional PHẦN 2 ppt

70 460 0
Beginning ASP.NET 2.0 E-Commerce in C# 2005 From Novice to Professional PHẦN 2 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I 49 featured products in the department page, in part because the complete list would be too long. The text above the list of featured products is the description for the selected department, which means you’ll need to store in the database both a name and a description for each department. In this page, when a particular category from the categories list is selected, all of its prod- ucts are listed, along with updated title and description text. In Figure 3-3, you can see how that page appears when selecting the “Birthdays” category. Also note the paging controls, which appear in any product listings that contain more than an established number of products. Figure 3-3. The “Birthdays” category In any page that displays products, you can click the name or the picture of a product to view its product details page (see Figure 3-4). In later chapters, you’ll add more functionality to this page, such as product recommendations. Darie-Watson_4681C03.fm Page 49 Thursday, September 15, 2005 5:42 AM 50 CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I Figure 3-4. The product details page Roadmap for This Chapter We’ll cover a lot of ground in this chapter. To make sure you don’t get lost on the way, let’s have a look at the big picture. The departments list will be the first dynamically generated data in your site, as the names of the departments will be extracted from the database. We cover just the creation of the department list in this chapter, in the form of a Web User Control, because we’ll also take a closer look at the mechanism that makes the control work. After you understand what happens behind the list of departments, you’ll quickly implement the other components in Chapter 4. In Chapter 2, we discussed the three-tiered architecture that you’ll use to implement the Web Application. The product catalog part of the site makes no exception to the rule, and its components (including the departments list) will be spread over the three logical layers. Figure 3-5 previews what you’ll create at each tier in this chapter to achieve a functional departments list. Darie-Watson_4681C03.fm Page 50 Thursday, September 15, 2005 5:42 AM CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I 51 Figure 3-5. The components of the departments list To implement the departments list, you’ll start with the database and make your way to the presentation tier: 1. You’ll create the Department table in the database. This table will store data regarding the store’s departments. Before adding this table, you’ll learn the basic concepts of working with relational databases. 2. You’ll add the GetDepartments stored procedure to the database, which (like all the other stored procedures you’ll write) is logically located in the data tier part of the appli- cation. At this step, you’ll learn how to speak with relational databases using SQL. Darie-Watson_4681C03.fm Page 51 Thursday, September 15, 2005 5:42 AM 52 CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I 3. You’ll create the business tier components of the departments list. You’ll learn how to communicate with the database by calling the stored procedure and sending the results to the presentation tier. 4. Finally, you’ll implement the DepartmentsList.ascx Web User Control to display a dynamic list of departments for your visitor, which is the goal of this chapter. You’ll implement the rest of the product catalog in Chapter 4. So, let’s start with the database. Storing Catalog Information The vast majority of Web Applications, e-commerce web sites being no exception, live around the data they manage. Analyzing and understanding the data you need to store and process is an essential step in successfully completing your project. The typical data storage solution for this kind of application is a relational database. However, this is not a requirement—you have the freedom to create your own data access layer and have whatever kind of data structures to support your application. ■Note In some particular cases, it may be preferable to store your data in plain text files or XML files instead of databases, but these solutions are generally not suited for applications like BalloonShop, so we won’t cover them in this book. However, it’s good to know there are options. Although this is not a book about databases or relational database design, you’ll learn all you need to know to understand the product catalog and make it work. For more information about database programming using SQL Server, you should read an SQL Server book such as Beginning SQL Server 2005 Programming (Wiley, 2005). Essentially, a relational database is made up of data tables and the relationships that exist between them. Because in this chapter you’ll work with a single data table, we’ll cover only the database theory that applies to the table as a separate, individual database item. In the next chapter, when you add the other tables to the picture, we’ll take a closer look at more theory behind relational databases by analyzing how the tables relate to each other and how SQL Server helps you deal with these relationships. ■Note In a real world situation, you would probably design the whole database (or at least all the tables relevant to the feature you build) from the start. However, we chose to split the development over two chapters to maintain a better balance of theory and practice. So, let’s start with a little bit of theory, after which you’ll create the Department data table and the rest of the required components. Darie-Watson_4681C03.fm Page 52 Thursday, September 15, 2005 5:42 AM CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I 53 Understanding Data Tables This section is a quick database lesson that covers the essential information you need to know to design simple data tables. We’ll briefly discuss the main parts that make up a database table: • Primary keys • Unique columns • SQL Server data types • Nullable columns and default values •Identity columns • Indexes ■Note If you have enough experience with SQL Server, you might want to skip this section and go directly to the “Creating the Department Table” section. A data table is made up of columns and rows. Columns are also referred to as fields, and rows are sometimes called records. Still, in a relational database, a good deal of hidden logic exists behind a simple list of data rows. The Department Table The database element of the product catalog is composed of tables, table relationships, and stored procedures. Because this chapter only covers the departments list, you’ll only need to create one data table: the Department table. This table will store your departments’ data and is one of the simplest tables you’ll work with. With the help of tools such as the Visual Studio .NET or Visual Web Developer, it’s easy to create a data table in the database if you know what kind of data it will store. When designing a table, you must consider which fields it should contain and which data types should be used for those fields. Besides a field’s data type, there are a few more properties to consider; we’ll learn about them in the following pages. To determine which fields you need for the Department table, write down a few examples of records that would be stored in that table. Remember from the previous figures that there isn’t much information to store about a department—just the name and description for each department. The table containing the departments’ data might look like Figure 3-6. Figure 3-6. Data from the Department table Darie-Watson_4681C03.fm Page 53 Thursday, September 15, 2005 5:42 AM 54 CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I From a table like this, the names would be extracted to populate the list in the upper-left part of the web page, and the descriptions would be used as headers for the featured products list. Primary Keys The way you work with data tables in a relational database is a bit different from the way you usually work on paper. A fundamental requirement in relational databases is that each data row in a table must be uniquely identifiable. This makes sense because you usually save records into a database so that you can retrieve them later; however, you can’t do that if each row isn’t uniquely identifiable. For example, suppose you add another record to the Department table shown previously in Figure 3-6, making it look like the table shown in Figure 3-7. Figure 3-7. Two departments with the same name Now look at this table, and tell me the description of the “Balloons for Children” depart- ment. Yep, we have a problem! The problem arises because there are two departments with this name. If you queried the table using the Name column and wanted to add new products to the “Balloons for Children” department, to change the department’s name, or to do literally anything, you would get two results! To solve this problem, you use a primary key, which allows you to uniquely identify a specific row out of many rows. Technically, a PRIMARY KEY is a constraint applied on a table column that guarantees that the column will have unique values across the table. ■Note Applying a PRIMARY KEY constraint on a field also generates a unique index by default. Indexes are objects that improve the performance of many database operations, speeding up your Web Application (you’ll learn more about indexes a bit later). A table can have a single PRIMARY KEY constraint, which can be composed of one or more columns. Note that the primary key is not a column itself; instead, it’s a constraint that applies to one or more of the existing columns. Constraints are rules that apply to data tables and make up part of the data integrity rules of the database. The database takes care of its own integrity and makes sure these rules aren’t broken. If, for example, you try to add two identical values for a column that has a PRIMARY KEY constraint, the database will refuse the operation and generate an error. We’ll do some experiments later in this chapter to show this. Darie-Watson_4681C03.fm Page 54 Thursday, September 15, 2005 5:42 AM CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I 55 ■Note Although a PRIMARY KEY is not a column, but a constraint that applies to that column, from now on, for the sake of simplicity, when we refer to primary key, we’ll be talking about the column that has the PRIMARY KEY constraint applied to it. Back to the example, setting the Name column as the primary key of the Department table would solve the problem because two departments would not be allowed to have the same name. If Name is the primary key of the Department table, searching for a row with a specific Name will always produce exactly one result if the name exists, or no results if no records have the specified name. An alternative solution, and usually the preferred one, is to have an additional column in the table, called an ID column, to act as its primary key. With an ID column, the Department table would look like Figure 3-8. Figure 3-8. Adding an ID column as the primary key of Department The primary key column is named DepartmentID. We’ll use the same naming convention for primary key columns in the other data tables we’ll create. There are two main reasons why it’s better to create a separate numerical primary key column than to use Name (or another existing column) as the primary key: • Performance: The database engine handles sorting and searching operations much faster with numerical values than with strings. This becomes even more relevant in the context of working with multiple related tables that need to be frequently joined (you’ll learn more about this in Chapter 4). • Department name changes: If you need to rely on the ID value being stable in time, creating an artificial key solves the problem because it’s unlikely you’ll ever need to change the ID. In Figure 3-8, the primary key is composed of a single column, but this is not a requirement. If the primary key is composed of more than one column, the group of primary key columns (taken as a unit) is guaranteed to be unique (but the individual columns that form the primary key can have repeating values in the table). In Chapter 4, you’ll see an example of a multivalued primary key. For now, it’s enough to know that they exist. Darie-Watson_4681C03.fm Page 55 Thursday, September 15, 2005 5:42 AM 8213592a117456a340854d18cee57603 56 CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I Unique Columns UNIQUE is yet another kind of constraint that can be applied to table columns. This constraint is similar to the PRIMARY KEY constraint because it doesn’t allow duplicate data in a column. Still, there are differences. Although there is only one PRIMARY KEY constraint per table, you are allowed to have as many UNIQUE constraints as you like. Columns with the UNIQUE constraint are useful when you already have a primary key, but you still have columns for which you want to have unique values. You can set Name to be unique in the Department table if you want to forbid repeating values, when the DepartmentID column is the primary key. (We won’t use the UNIQUE constraint in this book, but we mention it here for completeness.) We decided to allow identical department names because only site administra- tors will have the privileges to modify or change department data. The facts that you need to remember about UNIQUE constraints are •The UNIQUE constraint forbids having identical values on the field. • You can have more that one UNIQUE field in a data table. • Unlike with primary keys, a UNIQUE constraint can’t apply to more than one field. •A UNIQUE field is allowed to accept NULL values, in which case it can only accept one NULL value. • Indexes are automatically created on UNIQUE and PRIMARY KEY columns. Columns and Data Types Each column in a table has a particular data type. By looking at the previously shown Figure 3-8 with the Department table, it’s clear that DepartmentID has a numeric data type, whereas Name and Description contain text. It’s important to consider the many data types that SQL Server supports so that you can make correct decisions concerning how to create your tables. Table 3-1 isn’t an exhaustive list of SQL Server data types, but it focuses on the main types you might come across in your project. Refer to SQL Server 2005 Books Online, which can be freely accessed and downloaded from http://msdn.microsoft.com/sql/, for a more detailed list. ■Note Table 3-1 was created with SQL Server 2005 in mind, but these data types exist in SQL Server 2000 as well, and even SQL Server 7 comes close. The differences between SQL Server versions are reflected in details such as the maximum size for character data. To keep the table short, under the Data Type heading we’ve listed only the most frequently used types, while similar data types are explained under the Description and Notes heading. You don’t need to memorize the list, but you should get an idea of which data types are available. Darie-Watson_4681C03.fm Page 56 Thursday, September 15, 2005 5:42 AM CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I 57 Table 3-1. SQL Server 2005 Data Types Data Type Size in Bytes Description and Notes Int 4 Stores whole numbers from -2,147,483,648 to 2,147,483,647. You’ll use them for ID columns and in other circumstances that require integer numbers. Related types are SmallInt and TinyInt. A Bit data type is able to store values of 0 and 1. Money 8 Stores monetary data with values from -2 63 to 2 63 -1 with a precision of four decimal places. You’ll use this data type to store product prices, shopping cart subtotals, and so on. SQL Server also supports the Float data type, which holds floating- point data, but Float is not recommended for storing monetary information because of its lack of precision. A variation of Money is SmallMoney, which has a smaller range, but the same precision. DateTime 8 Supports date and time data from January 1, 1753 through December 31, 9999 with an accuracy of three hundredths of a second. A SmallDateTime type has a range from January 1, 1900 to June 6, 2079 with an accuracy of one minute. You’ll use this data type to store information such as order shipping dates. UniqueIdentifier 16 Stores a numerical Globally Unique Identifier (GUID). A GUID is guaranteed to be unique; this property makes it very useful in certain situations. In this book, we prefer to generate unique identifiers using other methods, but it’s good to know there are options. VarChar, NVarChar Variable Stores variable-length character data. NVarChar stores Unicode data with a maximum length of 4,000 characters and VarChar non-Unicode data with a maximum length of 8,000 characters. This data type is best used for storing short strings (note their length limitation) without fixed lengths. Char, NChar Fixed Stores fixed-length character data. Values shorter than the declared size are padded with spaces. NChar is the Unicode version and goes to a maximum of 4,000 characters, whereas Char can store 8,000 characters. When the size of the strings to be stored is fixed, it’s more efficient to use Char rather than VarChar. Text, NText Fixed Stores large character data. NText is the Unicode version and has a maximum size of 1,073,741,823 characters. Text has double this maximum size. Using these data types can slow down the database, and it’s generally recommended to use Char, VarChar, NChar, or NVarChar instead. When adding Text or NText fields, their length is fixed to 16, which represents the size of the pointer that references the location where the actual text is stored, and not the size of the text itself. The Text data type can be used to store large character data such as para- graphs, long product descriptions, and so on. We won’t use this data type in this book. Darie-Watson_4681C03.fm Page 57 Thursday, September 15, 2005 5:42 AM 58 CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I ■Note The names of the SQL Server 2005 data types are not case sensitive, and most programmers write them either in full uppercase or lowercase. We’ve cased them properly in the table for readability. Now let’s get back to the Department table and determine which data types to use. Don’t worry that you don’t have the table yet in your database, you’ll create it a bit later. For now, you just need to understand how data types work with SQL Server. If you know what these data types mean, Figure 3-9 is self-explanatory. DepartmentID is an Int, and Name and Description are VarChar data types. The little golden key at the left of DepartmentID specifies that the column is the primary key of the Department table. Figure 3-9. Designing the Department table You can also see the length of the VarChar fields. Note that “length” means different things for different data types. For numerical data types, the length is usually fixed (so it doesn’t show up in some designers, such as the one in Figure 3-9) and it specifies the number of bytes it takes to store one record, whereas for string data types (excluding Text and NText), the length specifies the number of characters that can be stored in a record. This is a subtle but important difference because for Unicode text data (NChar, NVarChar, NText), the actual storage space needed is 2 bytes per character. We choose to have 50 characters available for the department’s name and 1,000 for the description. Some prefer to use NVarChar instead of VarChar—this is actually a requirement when you need to store Unicode characters (such as Chinese text). Otherwise, the non-Unicode versions are usually preferred because they occupy half the size their Unicode pairs need. With large databases, the smaller size of the non-Unicode versions can make some difference. Binary, VarBinary Fixed/Variable Stores binary data with a maximum length of 8,000 bytes. Image Variable Stores binary data of maximum 2 31 - 1 bytes. Despite its name, this field can store any kind of binary data, not just pictures. In most circumstances, it’s easier and faster to store the files in the OS file system and store only their names in the database, but there are situations when it makes more sense to use the database for storing binary data. For BalloonShop, you’ll store the product images in the file system. Table 3-1. SQL Server 2005 Data Types (Continued) Data Type Size in Bytes Description and Notes Darie-Watson_4681C03.fm Page 58 Thursday, September 15, 2005 5:42 AM [...]... see it in action in the data access code, where it catches potential data access errors to report them to the administrator Darie-Watson_4681C03.fm Page 81 Thursday, September 15, 20 05 5: 42 AM CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I Sending Emails Speaking of reporting errors, in BalloonShop you’ll report errors by emailing them to the site administrator (or to the person you designate to handle... SQL Server Instance name (localhost\SqlExpress by default), and log in using Windows Authentication 2 Use the sp_grantlogin stored procedure to add a Windows user account to the SQL Server database This command grants the ASPNET account the privilege to connect to SQL Server Be sure to use the name of your local machine instead of MachineName EXEC sp_grantlogin 'MachineName\ASPNET' 3 After giving the... network path instead of (local) After specifying the server, you need to supply security information needed to log in to the server You can log in to SQL Server by either using SQL Server Authentication (in which case you need to supply a SQL Server username and password as shown in the code snippet) or by using Windows Authentication (also named Windows Integrated Security) With Windows Integrated Security,... are related to database access This is the most modern Microsoft data-access technology, and it can be used from any NET language ADO.NET is a complex subject that requires a separate book by itself, so we’ll cover just enough to help you understand how your business tier works For more information about ADO.NET, refer to Beginning ASP.NET 2. 0 Databases: From Novice to Professional (Apress, 20 05) The... visitor to come back later For any kind of error, it’s good to let the site administrator (or the technical staff) know about the problem Possible options include sending details about the error to a custom database table, to the Windows Event log, or by email At the end of this chapter, you’ll learn how to send an email to the site administrator with detailed information when an error happens In our... don’t have to supply a username and password because SQL Server uses the Windows login information of the currently logged -in user To log in using Windows Authentication, you’ll need to supply Integrated Security=True (or Integrated Security=SSPI) instead of User ID=username; Password=password The final part of the connection string specifies the database you’ll be working with Instead of setting the... trace If it isn’t handled anywhere, it’s finally caught by the NET Framework, which displays an error message If the error happens in an ASP.NET page during a client request, ASP.NET displays an error page, eventually including debugging information, to the visitor (The good news in this scenario is that ASP.NET can be instructed to display a custom error page instead of the default one— you’ll do that... additional information about fixing connection problems Let’s talk about configuring SQL Server to accept connections from within your web site, considering that you have done the installation procedures as explained in Appendix A If you’re using an external SQL Server instance, such as the one provided by your web hosting company, you’ll need to request the connection string details from the system administrator... existing procedure 4 Now test your first stored procedure to see that it’s actually working Navigate to the GetDepartments stored procedure node in Database Explorer and select Execute, as shown in Figure 3-13 Figure 3-13 Executing a stored procedure from Visual Web Developer 821 3592a117456a340854d18cee57603 69 Darie-Watson_4681C03.fm Page 70 Thursday, September 15, 20 05 5: 42 AM 70 CHAPTER 3 ■ CREATING... http://www.sitepoint.com/article/sql-injection-attacks-safe • This might be a matter of taste, but having the SQL logic separated from the C# code keeps the C# code cleaner and easier to manage; it looks better to call the name of a stored procedure than to join strings to create an SQL query to pass to the database Your goal for this section is to write the GetDepartments stored procedure, but first, let’s . table Darie-Watson_4681C03.fm Page 62 Thursday, September 15, 20 05 5: 42 AM 821 3592a117456a3 408 54d18cee57 603 CHAPTER 3 ■ CREATING THE PRODUCT CATALOG: PART I 63 ■Note To ensure consistency with the scripts in the. that require integer numbers. Related types are SmallInt and TinyInt. A Bit data type is able to store values of 0 and 1. Money 8 Stores monetary data with values from -2 63 to 2 63 -1 with. 3-1. SQL Server 20 05 Data Types Data Type Size in Bytes Description and Notes Int 4 Stores whole numbers from -2, 147,483,648 to 2, 147,483,647. You’ll use them for ID columns and in other circumstances

Ngày đăng: 09/08/2014, 14:20

Từ khóa liên quan

Mục lục

  • Beginning ASP.NET 2.0 E-Commerce in C# 2005: From Novice to Professional

    • Chapter 4 Creating the Product Catalog: Part II

Tài liệu cùng người dùng

Tài liệu liên quan