1. Trang chủ
  2. » Công Nghệ Thông Tin

BeginningASP.NET 2.0 with C# PHẦN 10 pps

84 252 0

Đ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

Thông tin cơ bản

Tiêu đề Beginning ASP.NET 2.0 with C# PHẦN 10 pps
Định dạng
Số trang 84
Dung lượng 2,44 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

You can right-click any database table in theDatabase Explorer and select Show Table Data to try this out for yourself.. Field Data Type Allow NullsNotice that one of the fields in this

Trang 1

8. At the end of this installation, you should see the screen shown in Figure B-9, asking you torestart your machine You should oblige by clicking Restart Now.

By chance, you may not see this screen As a general rule, you shouldn’t restart more often than sary, so if you’re not prompted to restart, don’t do it.

neces-Figure B-9

9. After your machine has restarted, the dialog box depicted in Figure B-10 is displayed, notifyingyou of a successful install (or any problems that were encountered) and reminding you to regis-ter the software within 30 days

Figure B-10

10. Click Exit and you will now be able to start up both Visual Web Developer and SQL Express.

SQL Server needs Internet access during installation, so make sure it can access the Internet Otherwise, the installation will fail.

653 Setup

Trang 2

Web Site Folder Setup

Next, set up the Websites folder with Windows Explorer, and create the folder C:\Websites\

WroxUnited(or use whichever drive is appropriate to your setup)

IIS Setup (Optional)

As we’ve already mentioned, Visual Web Developer Express comes with its own web server: the

ASP.NET Development Server, nicknamed Cassini However, some of you might want to use IIS way Note that it isn’t possible to run two versions of the web site concurrently, one on IIS and one onthe development server, because the database attaches itself to the ASP.NET Development Server andyou will find you can’t run it with IIS without detaching the database first

any-To use IIS, you must have Windows XP Professional, Windows 2000, or Windows 2003 Server installed.Windows XP Home Edition comes without IIS, and it isn’t possible to install it on Home Edition if you

do manage to get a copy of IIS To begin the install, follow these steps:

1. To install IIS go to the Start menu, navigate to Settings➪Control Panel, and click Add or RemovePrograms From the left-hand menu of the dialog box (shown in Figure B-11), select the

Add/Remove Windows Components icon This will bring up the Windows ComponentsWizard

Figure B-11

2. Make sure the Internet Information Services option is selected, as shown in Figure B-12.

To create a folder in Windows Explorer, select File➪New Folder and type in the

name Websites.

Trang 3

Figure B-12

3. Click Details and you can select which of the options to install (see Figure B-13) You won’t need

all of the options, although you can install them separately at a later point However, you must

make sure that you select the Common Files, the IIS snap-in, the Front Page Extensions, and theWorld Wide Web Services options, because these are necessary to work with ASP.NET 2.0 andVisual Web Developer Express

Figure B-13

4. Click OK and make sure you have the Windows CD handy for the installation

655 Setup

Trang 4

Create Alias

If you choose to install IIS and want to use the Wrox United sample web site on IIS, you will need to ate an alias so that IIS can recognize which application you mean and serve it accordingly The followingsteps walk you through creating an alias:

cre-1. From the Start menu, select Run Type MMC in the text box, and click OK In the MMC dialog

box that appears, select File➪Add/Remove Snap In Click the Add button and select IIS InternetInformation Services from the dialog box that appears, as depicted in Figure B-14

Figure B-14

2. Expand the Internet Information Services, as shown in Figure B-15 Under that will be yourcomputer’s name Expand that as well as the Web Sites option

Figure B-15

Trang 5

3. Right-click Default Web Site, and select New➪Virtual Directory from the menu to start the

wiz-ard Type WroxUnited as the Virtual Directory Name as in Figure B-16.

Trang 6

Figure B-18

6. Click Finish Close the MMC Console A save is optional, and you can supply a name if you sodesire

Wrox United Installation

Go to www.wrox.comand search for the dedicated page for Beginning ASP.NET 2.0 with C++ (ISBN:0470042583) When you are there, you can download the Wrox United application, which comes as a single downloadable zip file containing the database and application Download the zip file and save it

to the C:\Websites\WroxUnitedfolder you created earlier Next, unzip this file to C:\Websites\

It will automatically put files in the WroxUnited folder for you, so be careful not to extract it to

C:\Websites\WroxUnited, because you could end up with C:\Websites\WroxUnited\WroxUnited

In Windows Explorer, make sure that inside your C:\WebSites\WroxUnitedis an App_Datafolderand that it has four files

In particular, make sure that the following file names are present:

Trang 7

Network Service Enabling

The last step before you can test the application is that you might need to add Write permissions to theNetwork Service account This will allow ASP.NET to use the database and to read data from it and writedata to it, as is routinely required throughout the course of this book You can skip this step if you areusing Windows Server 2003, because the Network Service account has these permissions already enabled

by default If not, then you will almost certainly have to enable Write permissions first Here’s how:

1. Go to Windows Explorer and select the C:\WebSites\WroxUnited\App_Datafolder click it and select Sharing and Security Select the Security tab, shown in Figure B-19

659 Setup

Trang 8

Figure B-20

2. Click the Add button in the Wrox United Properties dialog box and in the Select Users or

Groups dialog box that appears Type NETWORK SERVICE into the text box and click Check

Names NETWORK SERVICE will become underlined, as shown in Figure B-21

Figure B-21

If the machine is joined to a domain, you must select the Locations button first and

pick the current machine, rather than the domain That’s because NETWORK

SER-VICE is an account on your machine By default, the dialog will attempt to add the

domain name, rather than the machine name.

Trang 9

3. Click OK You are returned to the Wrox United Properties dialog box This time, select the newNETWORK SERVICE option Scroll down and check the box next to Write (see Figure B-22).Click Apply, and then click OK.

Figure B-22

This will enable your account to access the database

Windows XP Home Edition Users Only

If, when you come to browse for a Security tab in Windows Explorer, you can’t find one, this is because youhave Windows XP Home Edition installed and you have a slightly more complex route to enable the cor-rect permissions Apparently, Windows XP Home Edition users just aren’t allowed to have the same kind

of power as their XP Professional counterparts To get around this, restart your computer in Safe Mode

To do this, restart your machine, and before the Windows XP logo appears, hold down the F8 key and

select Safe Mode Let XP continue and then log in as Administrator You’ll receive a warning about

run-ning in Safe Mode, but click Yes anyway Locate the C:\WebSites\WroxUnited folder in WindowsExplorer and right-click the App_Datafolder Select Properties and select the Security tab that has nowappeared Now go back to step 1 in the previous section and follow the instructions from there on At theend, though, shut down and restart your machine in normal mode before you continue to the next step

Checking the Installation with VWD and the ASP.NET Development Server

After you have successfully downloaded the Wrox United zip file, unzipped it, and enabled theNetwork Service, you are ready to check your installation Follow these steps:

661 Setup

Trang 10

1. Select the Start menu and navigate to All Programs Select the Visual Web Developer 2005Express Edition Icon at the bottom of the menu VWD will open.

2. Select File➪Open Web Site, and browse to C:\Websites\WroxUnited and click Open When theweb site has loaded into Solution Explorer, double-click default.aspxto open the file Pressthe F5 key to run the page and observe it in a browser You should see what appears in Figure B-23 in your browser

Figure B-23

Checking the Installation with IIS

Follow this step only if you have installed IIS and intend to use it as your main web server To open

WroxUnited with IIS, start Internet Explorer and type http://localhost/WroxUnited into the Address line.

The web site should start and display what’s shown in Figure B-24

Please note that while Figure B-22 is seemingly identical to Figure B-21, the Address line reveals a smalldifference If you are running your site on ASP.NET Development Server (the free web server withVWD), you will get the following line (potentially with a different number):

http://localhost:1231/WroxUnited

This indicates that the web server is running on port 1231 The ASP.NET Development Server will ily assign a port number in the URL If you are running the web site on IIS, then you see the following line:

arbitrar-http://localhost/WroxUnited

Trang 11

Figure B-24

IIS by default runs on port 80, and this doesn’t need to be specified in the URL

Occasionally, if port 80 is taken by another process, IIS will default to http://localhost:8080, or youmight have to specify it yourself if you get an error message saying Unexpected error 0x8ffe2740occurred

This means that another application is using port 80 To alter this, you need to start the IIS manager fromAdministrative Tools in the Control Panel, right-click the Default Web site in the left panel, and select

Properties From the Web Site tab, change the number there from 80 to 8080, or if 8080 is taken then 8081,

or the first one free above that number

Troubleshooting

By and large, installation with SQL Express and the ASP.NET development is straightforward However,

if you are trying to use SQL Server 2005 rather than SQL Express, you should run through the followingextra steps:

1. Add [machine\ASPNET]and [NT AUTHORITY\NETWORK SERVICE]as logins, substitutingmachine with your machine name

2. Attach the database (wroxunited.mdf), making ASPNET the db_owner

3. Add [machine\ASPNET]and [NT AUTHORITY\NETWORK SERVICE]as database users

4. Change the connection strings in web.config That should be all for the WroxUnited database.Then there’s the providers, which can be added to either the WroxUnited database or to a sepa-rate one

663 Setup

Trang 12

5. Run aspnet_regsql(in the framework directory), to add user/roles/etc tables/procstothe appropriate database.

6. Add provider sections in web.config, for <membership>, <roles>, and <profile>, settingthe default provider for each to the new provider added These providers should point at theConnectionString for the database (which will be either WroxUnited or a new connection string

if you’re using another database)

Note that if you are using a different version of SQL Server than 2005, it isn’t possible to just attach thedatabase to the different version If you are using the full version of 2005 and you encounter the followingproblem:

Server Error in ‘/WroxUnited’ Application

Failed to generate a user instance of SQL Server due to a failure in copying

database files The connection will be closed

Description: An unhandled exception occurred during the execution of the currentweb request Please review the stack trace for more information about the error andwhere it originated in the code

Exception Details: System.Data.SqlClient.SqlException: Failed to generate a userinstance of SQL Server due to a failure in copying database files The connectionwill be closed

you will need to do the following:

1. Reboot windows.

2. Log in as Administrator (if you aren’t running with Admin privileges).

3. Delete the C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESSdirectory

You might need to logout and log back in as a “normal” user if you normally run with non-admin privileges

If this doesn’t work, try the following solution — there is a known problem with remote logging on andSQL Express, which the following steps should circumvent:

1. Go to the SQL Configuration Manager

2. Right-click SQL Express and select Properties

3. From the Logon tab, change the account from Network Service to Local System.

4. Try to run it again.

Apart from that, if you encounter a problem go to http://forums.asp.netor http://p2p.wrox.com

and check to see if your problem is addressed there

Trang 13

Wrox United Database Design

Throughout this book, you’ve seen examples based on the fictional Wrox United soccer team website The application relies on a SQL Server database, supplied with the code downloads for thisbook (available at www.wrox.com) This database stores details of the players in the team, fixturesand results, news items, orders from the shop, and so on

This appendix is not intended to provide a thorough overview of database design principles, and

as such, we recommend that you read Wrox’s Beginning Database Design.

The database schema looks like Figure C-1

Figure C-1

Trang 14

This diagram illustrates the tables that exist within the database, and the relationships between thosetables For example, players score goals, goals are scored at fixtures, match reports are written about spe-cific fixtures, and so on Many tables relate to other tables in the database, but there are some tables thatstand on their own; for example, the News table, which stores news articles This table doesn’t link todata stored in any other table Notice also that the Orders, Products, and OrderLines tables are separatefrom the rest of the database — these tables are used to store data relating to orders from the WroxUnited shop.

This appendix walks through the structure of each of the tables in the database and describes the tionships between them

rela-Players and Matches

The players on the Wrox United team are involved in many fixtures, and several related tables in thedatabase store related data for matches Take a look at these tables first

The Players Table

The following shows the structure of the Players table

This table is typical of all database tables in that it has the following:

A primary key field that uniquely identifies each row in the database

❑ Fields designed to store textual data about each player (in varcharfields)

❑ Fields that store date and time information

❑ Flags indicating whether or not different fields require values

In this table, the primary key is the PlayerID field, which stores numeric values (integers) that areunique to each player in the database This field, along with the FirstName and LastName fields, ismarked as not allowing null values In other words, if you enter a row of data in the table, you must

Trang 15

enter values for each of these fields However, the PlayerID field will be filled with an auto-generatednumber for you (due to the way it is configured), so the only data you must enter when you create a newrow is the full name of the new player The remaining information describing the player is optional Youdon’t have to specify which position the player occupies, and you don’t have to specify when he or shejoined.

Note that a varcharfield is a field that stores character data of varying length The number in brackets

is the maximum number of characters that can be stored in that field If the field contains less than the maximum length, it occupies less space in the database Acharfield, by comparison, always takes up the same size in the database, no matter how much of the available space is filled with data.

Figure C-2 shows an example of some data from the Players table

Figure C-2

This screenshot comes straight from Visual Web Developer You can right-click any database table in theDatabase Explorer and select Show Table Data to try this out for yourself

The Goals Table

The Goals table relates directly to the Players table, because players score goals during a match The lowing shows the structure of the Goals table

fol-667 Wrox United Database Design

Trang 16

Field Data Type Allow Nulls

Notice that one of the fields in this table is the PlayerID field, which will store an integer value sponding to the ID of one of the players in the Players table, so if Dave Dickenson scored the first goalfor Wrox United, the goal in the table with GoalID of 1 will have a PlayerID of 4 Dave could later scoreanother goal for Wrox United, so another record in the Goal table would be created with another unique

corre-value for GoalID, but with the same PlayerID This type of field is called a foreign key because it relates

directly to a primary key in another table

There is another field in the Goals table for storing ID values, which is the FixtureID field This linkseach goal to a particular fixture Because players could score many goals at a single fixture, the relation-ship between the Fixtures table and the Goals table is similar to that of the Players table and the Goalstable

The Fixtures Table

The Fixtures table is structured as shown here

For each match played by the Wrox United team, there is an entry in the Fixtures table Because fixturescan be arranged several months in advance, the fixture date has to be entered as soon as the fixture isarranged, and the opponents have to be entered The number of goals scored can be entered later, afterthe match has been played

This sort of relationship — where one fixture can contain many goals, or where one

player could score many goals — is known as a one-to-many relationship.

Trang 17

The MatchReports Table

After each match has taken place, it’s up to the reporters to write up the details of the match so that fanscan read all about it later These reports are stored in the MatchReports table, which is structured like asshown here

This table also links to the Fixtures table by including a FixtureID field in this table, linking a matchreport to a specific fixture The MemberName field stores the name of the reporter

The Gallery Table

The Gallery table is used to store details of pictures uploaded by fan club members The fields defined inthis table are shown here

Each picture can relate to a specific fixture (notice the FixtureID field); however, because this field allowsthe use of null values, this implies that pictures do not necessarily have to relate to fixtures

Standalone Tables

The two standalone tables in the database are the Opponents table and the News table

The Opponents Table

The Opponents table stands on its own in the database, and is defined as shown here

The reason the Opponents table is on its own is a bit unfortunate, but the opposing team may decide to change its name at some point in the future, which would change the name of all fixtures that Wrox United played against them in the past if they were related By keeping the tables separate, and only using a name for each team, the name of the opponent in any particular match is preserved. 669

Wrox United Database Design

Trang 18

Field Data Type Allow Nulls

Name varchar(50) Yes

This table can be updated with results of matches to maintain a tally of how well the Wrox United team

is performing in the league

The News Table

The News table, described here, contains all of the news stories from the front page of the Wrox United site

Notice that each news item requires that a date be entered for each story, so that a story can remain den until a certain date has passed

hid-Wrox United Store Tables

The online shopping experience on the Wrox United site relies on data stored in three tables: the Orderstable, the Products table, and the OrderLines table These tables are heavily reliant on each other

The Orders Table

The Orders table, described here, contains a unique ID containing the main order details for an order

Trang 19

Field Data Type Allow Nulls

In this table, you’ll notice that most of the fields are marked as mandatory (not allowing null values).This highlights the fact that orders must have full address details before an order can be fulfilled A cou-ple of less familiar field types are in here too The nchardata type will always take up 10 charactersspace in the database, and the nin the name indicates that the data stored could contain Unicode charac-ters The other unfamiliar data type is money, which (as the name implies) can be used to store monetaryvalues

Notice that there are no details in this table about which products have been bought in a particularorder This information is stored in the OrderLines table

The OrderLines Table

The OrderLines table, described here, links the Products table to the Orders table, indicating which itemshave been bought in a particular order

671 Wrox United Database Design

Trang 20

Because an order can contain one or many products, there is a foreign key link here to the Products table.However, because many different orders can be for the same product, there is also a foreign key link here

to the Orders table This means that an individual line in this table stores details of one item, and oneorder number If you order more than one of a specific product, the Quantity is increased for the orderline, but you won’t end up with a new OrderLineID

The Products Table

The Products table, described here, contains details of all of the products that can be bought from theshop

This simple table provides data about products, and is used both when users are browsing the shop andwhen they’re buying items from the shop

The relationship between the Orders table and the Products table is a many-to-many

relationship In this situation, there has to be a central table that has one-to-many

relationships to both tables, and this is called the Join table.

Trang 21

VWD Database Explorer

When you’re designing pages that work with data, you frequently need to check the metadata, forexample, to confirm the data type of a field You also want to test your pages by quickly modifyingthe data in tables Furthermore, in some cases, you want to add a small and simple table to adatabase, such as a list of shippers In the past, these database tasks required that you leave yourweb editor to open a second window with a database management tool Visual Web Developeroffers a built-in tool named the Database Explorer that can perform these tasks without the needfor a separate management tool Some functions are performed directly and others invoke a wiz-ard to step you through the task

This appendix covers the various techniques for working with the Database Explorer

Opening the Database Explorer

You can view the Database Explorer either by choosing Menu➪View or by pressing Ctrl+Alt+S.After it is open, the Database Explorer by default stacks on top of the Solution Explorer on theright side of the screen You can move it to a new dock location by dragging its title bar

Adding an Existing Database to the Database Explorer

The technique to connect the Database Explorer to a database depends on the type of database.The following three sections cover the Microsoft databases Most other databases (such as Oracle

or MySQL) will be the same as connecting to a SQL Server

If you mess up the layout, you can return to the default by choosing Menu➪Windows➪Reset Windows Layout.

Trang 22

Accessing Files

Follow these steps:

1. On the Database Explorer toolbar, click Connect to Database, and from the first page of the ard, select Microsoft Access Database File, as shown in Figure D-1

Trang 23

SQL Databases on a SQL Server (Including SQL Server Express)

Follow these steps:

1. On the Database Explorer toolbar, click Connect to Database, and in the first page of the wizard(shown in Figure D-3), select Microsoft SQL Server

Figure D-3

In the next dialog box, the Data Source section is locked — it actually means the kind of datasource, not the name of the database

2. Continuing on the Add Connection screen, for the Server Name text box, there are two options

If you are using a full install of SQL Server, select the server name If you are using SQL Server

Express (as we do in this book), type the following syntax exactly: (local)\SQLExpress, as

shown in Figure D-4

Figure D-4

675 VWD Database Explorer

Trang 24

Note the potential confusion when using SQL Server Express Your PC name will be listed in thedrop-down box of servers, but that is not the server you want to specify You must type into theserver name box the specific syntax to point to your local machine’s instance of SQL ServerExpress.

3. Keep the choice for logon information set to Windows (see Figure D-5) unless you have oped an authentication table in SQL Server

devel-Figure D-5

4. After you have selected the server name, you can drop down the list of databases Test the nection and then click Finish to see your new data connection

con-Saving SQL Databases as an MDF File

For highest performance, data is kept in SQL Server without an external file structure But for portability,

a database can be configured to save its data in a Windows file that can be copied to a new server Thefile will have an extension of mdf We use an mdf file to distribute data in this book (The alternativewould be to have you download a long SQL script that would build the entire database internally inyour server and populate its data.) Connecting to an mdf file is very similar to connecting to AccessFiles Just follow these steps:

1. On the Database Explorer toolbar, click Connect to Database, and select Microsoft SQL ServerDatabase File, as shown in Figure D-6

Figure D-6

2. Browse to the file and add logon information if needed (see Figure D-7)

3. You have the option to test the connection and then it is added to your list in the Database Explorer

Trang 25

Figure D-7

V iewing Database Diagrams

The VWD Database Explorer provides a visual presentation of your database’s objects along with thecapability to drill down into each object’s properties Follow these steps to walk through a diagram ofyour database:

1. Within the Database Explorer, expand your Data Connections and then expand your database.When you expand the Database Diagrams (see Figure D-8) the first time, you may be asked toestablish yourself as the dbo (database owner) Click Yes Right-click the Database Diagram objectand add a new diagram If asked, accept the creation of elements needed to build the diagram

Figure D-8

677 VWD Database Explorer

Trang 26

2. Add tables as desired and close the Add Table dialog box (see Figure D-9).

Figure D-9

The diagram can be so large that it is easy to miss tables Note the Windows-standard horizontaland vertical scroll bars to navigate the diagram (see Figure D-10)

Figure D-10

Trang 27

3. You can rearrange the tables (the relationship lines will automatically adjust) Start by changingthe zoom size to 30% or so to be sure you see all of the tables and then do some rearranging Thezoom window is on the diagram toolbar, shown in Figure D-11 set to 30%.

Figure D-11

4. Increase the zoom size to be able to read the data For example, after rearrangement, 70% showsall the tables for Wrox United, as shown in Figure D-12

5. Right-click the title bar of a table (for example, Players) and select Properties from the menu In

the Properties box (in the lower right of the monitor), you can view parameters such as the

Identity column Right-click one field (see Figure D-13) of a table and select Properties to see how

that column has been configured, including the data type and length

6. Carefully place the tip of the mouse arrow on a relationship line (for example, between Fixturesand MatchReports) so that the mouse arrow changes to a horizontal double-ended arrow Right-

click this relationship and select Properties to view data on the relationship, including

enforce-ment rules, as shown in Figure D-14

679 VWD Database Explorer

Trang 28

Figure D-12

Figure D-13

Trang 29

Figure D-14

7. You can also print the Database Diagram or save it to include in documentation for the site.Note that there are tools to position page breaks at specific axes of the diagram, as well as a toolthat allows you to add a text box of notes

Exploring a Table’s Str ucture

In addition to the Database Diagram, you can look at tables through the Table node of the DatabaseExplorer, as follows:

1. Starting in Database Explorer, expand the list of databases and then the database of interest.Expand the Tables node and select a table name (for example, MatchReports) In the Propertieswindow, shown in Figure D-15, you will see the approximate number of records

Figure D-15

681 VWD Database Explorer

Trang 30

2. Double-click a table name to open a list of the columns (fields) and populate the Properties dows with data on the table as a whole, as shown in Figure D-16.

win-Figure D-16

These metadata can be changed in this view, assuming that you have the rights to make changes

to the database structure

Obser ving and Editing Data of Existing Tables

If you right-click a table name in the Tables node of Database Explorer, you’ll see an option to ShowTable Data This is a quick way to find out if your data-enabled web pages are actually carrying out theirtasks You can also add, modify, or delete records to test results in data-reading pages

Be extremely careful about changing data with the Show Table Data tool For example, deletions orchanges of customers may divorce them from their orders In some databases, the addition of a recordmay require the addition of a partner record in another table A simple correction to a spelling mistakemay cause a failure to properly look up data that is based on the old spelling If you thoroughly under-stand the schema and are changing independent data, you may avoid trouble But in most cases, it isbetter to make revisions based on the interface that ensconces proper validation, limits, and controls

Trang 31

Creating a New Database

It is rare that you will use VWD to create a database from scratch Good databases require the kind ofplanning and implementation tools that come with your database management system However, in thecase of a small and simple database, VWD does offer the necessary planning and implementation tools.You can add a new database in two ways: directly in the Database Explorer or by adding a SQL Databasethrough the Add New Item menu in Solution Explorer

Follow these steps to create a database in Database Explorer:

1. In the Database Explorer, right-click Data Connections and select Create New SQL ServerDatabase

2. Select a server If you’re using SQL Server Express, use this exact syntax for the server name:

(local)\SQLExpress Use Windows authentication unless you have created an authenticationscheme internal to SQL Server Express Type the name of the new database into the bottom text box.Database Explorer will automatically add the database to its list and you are ready to createtables and add data

You can also create a new database directly in the Solution Explorer This technique is very similar to thepreceding procedure except for the first few steps:

1. Start in the Solution Explorer and right-click the root of the web site Select Add New Item andselect the template of type SQL Database

2. When prompted, agree to add to the App_Datafolder

VWD will now roll you over to the Database Explorer where you will see the new database andfolders for its objects (albeit empty) You can now create tables, add data, and perform other tasks

Creating a New Table and Adding Data

Tables can be added and populated in the Database Explorer, as follows:

1. Expand the database, right-click the Tables node, and select Add New Table from the menushown in Figure D-17

Figure D-17

683 VWD Database Explorer

Trang 32

2. In the resulting list of columns, enter the names and data types For example, as shown inFigure D-18, a new table that holds a schedule of reporter’s interviews with the players wouldstart with a column (field) for InterviewID.

4. Set the primary key by selecting a field and clicking the key tool in the table’s toolbar

5. Finish by choosing Menu➪File➪Save Table

Examining and Creating V iews

Views provide a set of data Instead of returning information directly from a table, a view returns onlycertain fields, modified fields, or records In many databases, the security rules will allow a web site torequest a view but not directly request data from a table — this provides a level of control for thedatabase administrator For example, a table of employees may hold a field for salary level A view that

Trang 33

is authorized for the accounting department would include that field, but other users only have access toviews that do not include the salary data Views are also useful for creating hybrid data, such as combin-ing a NameFirst field and a NameLast field to show both names in a single field of a list box.

You can do a basic exercise where you create a view that would support a selection ListBox of Players.You want the view to create two fields — the first is the player’s ID and the second is a combination ofthe player’s last and first names, separated by a comma Follow these steps:

1. In Database Explorer, expand your database, right-click the Views node, and select Add a NewView This opens the designer for a new view in the background, and in the foreground, theAdd Table dialog (see Figure D-19) will open

Figure D-19

2. In the Add Table dialog box, select Players and click Add Close the dialog box

3. Before you go on, experiment with turning on and off the panels to display a view From left toright, they are the Diagram, Query, SQL Statement, and Results Because you are making a smallview, you can display all four Figure D-20 shows the four panels On the top is the pane oftables, showing just the Players table with the single field of PlayerID selected The next paneldown is the query designer, which shows the single field selected The next panel shows thevery simple SQL statement: SELECT PlayerID FROM dbo.Players The bottom panel showsthe results of choosing Query Designer➪Run to produce the results table

685 VWD Database Explorer

Trang 34

Figure D-20

4. Click the check box next to the PlayerID field in the Player table of the Diagram View (the toppanel) and note that the field is added to the Query and SQL Statement panels

5. In the Query panel, go to the second row and type FullName into the alias cell In the left

col-umn, type LastName + ‘, ‘ + FirstName.

6. Click the execute SQL tool (the red exclamation point) to see the results, displayed in Figure D-21

Trang 35

Figure D-21

7. Order the players’ names by last name SQL does not like to order on a created (or alias) field, so

go to the third row of the Query panel and add the LastName field Turn off its Output option.Set the Sort Order column to 1, meaning this is the first criterion for sorting In the Sort Type,VWD will automatically set the order to Ascending These four changes are shown in Figure D-22 This step tells SQL to sort according to the last name, but not to output the LastName asits own field Execute the SQL

687 VWD Database Explorer

Trang 36

Figure D-22

8. Press Ctrl+S and save the view as PlayersForSelectionList You now have a new view that can

be used in a selection list of a web page — for example, PlayerDetails.aspx, for which thedata controls follow Note that in the DataSource1(supporting the list box), you are not read-ing from the Players table Rather, you read from the PlayerSelection view That view includesyour new field FullName, which you can set as the DataTextFieldin ListBox1:

<asp:ListBox ID=”ListBox1” runat=”server”

Trang 37

Examining a Stored Procedure (SPROC)

Like the other objects explored in this appendix, you can examine, edit, and create stored procedures, orSPROCs SPROCs are a set of one or more SQL commands that, as a group, carry out a task TheDatabase Explorer offers a node for SPROCs, which can be expanded A single click selects a SPROC andshows, in the Properties window, if it is encrypted A double-click opens the SPROC, which can then beedited (assuming you have the rights to change the object)

The design of SPROCs is beyond the scope of this text, but you can take a quick look at one For ple, in the Database Explorer, you can expand the WroxUnited database and then expand StoredProcedures Then you can double-click usp_OrderAdd to open it and view the following code In thissimple SPROC, only one actual SQL statement gets executed:

exam-ALTER PROCEDURE dbo.usp_OrderAdd(

ASINSERT INTO Orders(MemberName, OrderDate, Name, Address, County, PostCode,Country, SubTotal, Discount, Total)

VALUES (@MemberName, GETDATE(), @Name, @Address, @County, @PostCode, @Country,

@SubTotal, @Discount, @Total)RETURN SCOPE_IDENTITY()

689 VWD Database Explorer

Trang 38

This SPROC has three parts The first and last lines establish the frame of the procedure and declare itsname The second section, within parentheses, names the parameters that will be used to carry out theprocedure The third part, the INSERT INTOstatement following the AScommand, describes the oneSQL statement to actually execute.

❑ You can examine both data and metadata The latter includes the list of fields in a table anddetails about how those fields are structured, including their exact spelling, data type, size, andother parameters that will be important when designing a page to use the fields

❑ When creating a database, table or view, or SPROC, the Database Explorer will kick off a wizard

to guide you through the process Keep in mind that when referring to your SQL Server Expressinstall, you must use the syntax of (local)\SQLExpress

❑ For two reasons, use particular caution when modifying data or metadata for existing

databases First, others may be expecting the database to be in its original state for their WebForms or Windows forms Second, you may not be aware of the constraints and relationshipsthat can be ruined by incorrect changes in the data or structure

Trang 39

CSS and HTML Quick Reference

This appendix provides a quick reference to CSS and HTML It’s not meant to be an exhaustiveand complete list of all HTML controls, their properties and the CSS properties, but rather to givethe most common uses

Styling Pages and Controls

You can style controls, or change their look and feel, in two ways: with properties of the control orwith Cascading Style Sheets (CSS) Ultimately, both achieve the same thing, making the controllook the way you want it to, but in practice, they are very different Both Visual Web Developerand Visual Studio 2005 use properties when setting the style for controls For example, if you drop

a GridViewonto your page and AutoFormat it with the Autumn format, you get the following:

<asp:GridView ID=”GridView1” runat=”server” BackColor=”White”

BorderColor=”#CC9966” BorderStyle=”None” BorderWidth=”1px” CellPadding=”4”>

<FooterStyle BackColor=”#FFFFCC” ForeColor=”#330099” />

<RowStyle BackColor=”White” ForeColor=”#330099” />

<PagerStyle BackColor=”#FFFFCC” ForeColor=”#330099”

Trang 40

❑ It makes the code hard to read Not only is it more text to read through, but the properties aren’talways in a logical order For example, on FooterStyleand RowStyle, the BackColorand

ForeColorare next to each other, but on the HeaderStyle, there is a Font-Boldattributebetween them

❑ There is extra text, bulking out the page With lots of styling applied to lots of controls, the pagesize can increase, which can lead to performance degradation

❑ It’s hard to amend if you decide to change colors AutoFormat works fine, but if you want tom colors, you have to change each property individually

cus-CSS solves this problem by abstracting the actual styling away from the control, leaving the control withjust a simple reference to the styles being used This is the CssClassproperty for web controls or the

classproperty for HTML controls The GridViewcould now be as follows:

<asp:GridView ID=”GridView1” runat=”server” CssClass=”MyGrid”>

Creating Inline Styles

To create inline styles, you use the <style>element, which is usually placed within the <head>ment For example:

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

TỪ KHÓA LIÊN QUAN