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

Beginning ASP.NET 2

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

Componentization

There is actually a third option called deployment pre-compilation, which is for full compilation of your project prior to deployment. You’ll learn a little more about this in Chapter 16.

The App_Code Folder

If you create an App_Code folder in your project, any code you place in that project will automatically be compiled when you run the project. It’s a far more robust solution than the old \bin folder, and for that reason we recommend using it for any code other than code-behind. The reason we suggest not using it for code-behind is that it is easier in VWD to keep your code files attached to the page they are related to; otherwise viewing them could be a pain.

So not only can you organize your code and in which pages it is placed, but ASP.NET 2.0 dictates a different structure for ordering where those pages are placed.

Data Layers

While you’ve looked at how code and content can be successfully separated, there is a third dimension to our discussions, namely that of the data. Throughout this book we’ve paused to reflect briefly on various aspects of the history of the Internet and the Web, while trying to keep you away from a huge lecture on the entire subject. Once again you’re going to have another quick history lecture to help you understand the purpose of the next ASP.NET 2.0 feature.

Two-Tier Applications

We don’t really want to rewind too far back, so let’s jump in halfway. Once HTML started getting beyond the universities, it became necessary to provide something more than just static text and images. One of the first ways in which web pages were made dynamic was to be able to access a database. The browser was one tier, and the database was the second tier. In this scenario, the browser dealt with rules about the business/application and user interface.

The term business rules is used to encompass any part of the application logic that isn’t the user interface or the database. If the application isn’t being used for a business, then the term application logic might be more applicable, although they mean the same thing.

The data retrieval and manipulation was performed by another separate database application, such as SQL Server or Microsoft Access. It would handle the data storage and retrieval device for the application. These two-tier applications were also commonly know as client-server applications. A typical client-server application is depicted in Figure 10-6.

359

Chapter 10

REQUEST

Client

Server

RESPONSE

Figure 10-6

The other popular variation on the two-tier application saw the business rules/application logic being executed on the database system. Such applications would commonly use stored procedures to manipulate the database (or in some cases triggers). A stored procedure is a query that is stored on the database. It can be called by the client application and then run on the server. It would contain rules about the business as well. For example, if you had a league table on Wrox United that awarded three points for a win and one point for a draw, then in the database query it would somehow have to record that when one side scores more goals than another side, it is worth three points. This is a business rule. It doesn’t matter to the database how many points you add on to the win; however, your league table would fail to work properly if you added two or five points for a win.

Three-Tier Applications

The big difference with three-tier applications is that business rules are no longer located on either the client or the database. They are stored and run on a system in between the client and the server. The advantage of this is that the business rules server can ensure that all of the business processing is done correctly. There is now a third layer interface, business rules and data. The introduction of the data tier is illustrated in Figure 10-7.

REQUEST

Client

Server

BUSINESS

RULES

RESPONSE

RECORDS QUERY

Data

Source

Figure 10-7

In a three-tier application the client never accesses the data storage system directly. You can make changes to the business rules and this would mean you could change any part of the system without having to alter the other two parts. As the three different sections of the application communicate via interfaces, and as long as the interface between the code and application front-end remains the same, the internal workings of each part can be changed without affecting the rest of the application. The advantages of doing this are

360

Componentization

similar to those for keeping code and content separate. Typically a database is managed by a database administrator (DBA), and it might even be managed by a separate company. The web developer as jack-of- all-trades would previously have been required to know the intimate workings of the database, when really he shouldn’t be interfering there at all. So this brings us to the end of our little excursion, because you can now look at a new feature in ASP.NET 2.0 that allows you to separate your applications more simply into three tiers.

What’s New in ASP.NET 2.0

In ASP.NET 2.0, you are no longer restricted to binding only to data controls; you can also bind to separate business controls via the ObjectDataSource control.

Using the ObjectDataSource Control

The new ASP.NET ObjectDataSource control allows you to declaratively bind data controls such as the GridView, DataList, and DropDownList controls to a separate business control or a data component. Previously you could only bind the controls directly to a database. This new development enables the separation of your business rules from your content and your data.

ObjectDataSource is a more difficult control to explain than a GridView or DropDownList control, so rather than wasting excessive verbiage, it’s quicker to show you exactly what the ObjectDataSource control does in an example. We’re actually going to do two examples to show it in action. The first example we’ll show you how to create a data component to return a list of players from the Players table. We’ll split this Try It Out into two sections, the first section where we create the ObjectDataSource itself and the second where we bind our ObjectDataSource control to a GridView control. The resulting output will be completely non-editable. In the second example, we’ll use the Try It Out to create a data component that can not only read from the Wrox United database but also write data to it. We will create and bind the data component in this same example which will make it quite lengthy.

The data component that you create in both examples will consist of an XSD schema file (.xsd). This file describes the data you require and defines which methods will be used to read and write data. This doesn’t require any code or knowledge of XML schemas because when you run the application, the .xsd file is compiled for you and performs all of the tasks needed.

Let’s start by creating the data component for our read-only example.

Try It Out

Creating the Data Component

1.Open Visual Web Developer and select Open Web Site. From the C:\BegASPNet2\Chapters\ Begin\Chapter10 folder, select ObjectDataSource and click OK.

2.In Solution Explorer, right-click the name of your web site, select Add ASP.NET Folder, and select App_Code.

3.Right-click the App_Code folder and select Add New Item from the list.

4.From the Visual Studio installed templates, click DataSet.

5.Rename the DataSet ods.xsd and click Add.

6.Next, VWD will start the TableAdapter Configuration Wizard. Be patient here, because this one really does take a while to kick in.

361

Chapter 10

7.When it finally arrives, select ConnectionString(Web.config) from the drop-down list (see Figure 10-8) and click Next.

Figure 10-8

8.Next you get a page where you can choose to use SQL statements or stored procedures. Select the Use SQL statements radio button (as shown in Figure 10-9) and click Next.

Figure 10-9

362

Componentization

9.On the next wizard screen you can define the SQL statement. Type the following SQL statement into the “What data should be loaded into the table” area of the dialog:

SELECT PlayerID, FirstName, LastName, Position, DateJoined, DateLeft FROM Players

10.After entering the SQL statement, click Next. You can now define which methods the component will expose. Uncheck the Fill a DataTable checkbox and make sure that the Return a DataTable checkbox is checked (see Figure 10-10). In the Method name box, type GetPlayers. This method is used later to retrieve the data. Uncheck the final checkbox.

Figure 10-10

11.Click Finish. In Figure 10-11, you can see the data component in the designer. It shows both the data you selected and the method you created.

Figure 10-11

12.Save the data component and close the component designer.

363

Chapter 10

13.Select Build Build Web Site to compile the component (note this won’t produce anything viewable).

How It Works

The data component is now usable as a data source within a Web Form. You’ve used the wizard to create the component for you, to select the fields from the database, and also to name the method that you want to be able to call this component by.

The next step is to bind to this component. To do this, you can create and configure an ObjectDataSource control. You can then add controls, such as the GridView control, to the page and bind them to the data source control.

Try It Out

Binding to the ObjectDataSource Control

1.Open the Default.aspx from Solution Explorer and switch to Design View.

2.Open the Toolbox and from the Data section drag an ObjectDataSource control onto the page.

3.Select the Toolbox again, and from the Data section drag a GridView control onto the page.

4.Click the black arrow on the top-right corner of the ObjectDataSource control. The Common Tasks box appears with the words Configure Data Source. Click this.

5.In the dialog that appears, there is a single drop-down list asking you to choose your business object (see Figure 10-12). There should only be one, the odsTableAdapters.PlayersTableAdapter; select that and click Next.

Figure 10-12

364

Componentization

6.On the next screen (shown in Figure 10-13), under the Select tab in the Choose a method drop-down box the GetPlayers(), returns PlayersDataTable method should be displayed. Select this and click Finish (the other methods are automatically picked for you).

Figure 10-13

7.Click the black arrow on the top-right corner of the GridView control and from the Choose Data Source list that appears, select ObjectDataSource1. The Grid will update in Design View.

8.Open the Properties window and check that the DataKeyNames property is set to PlayerID.

9.Run the application, and you will see Figure 10-14 in your browser:

365

Chapter 10

Figure 10-14

How It Works

You started by creating an instance of an ObjectDataSource control. To give it its functionality you attached it to the GetPlayers() method that was specified in the data component. The GetPlayers() method was created in the previous Try It Out. This method returns the results of the SQL statement, available as a DataTable object. The DataTable object is an object that the GridView (and indeed all data controls) can bind to. If you go back and look at the source that has been created, you can see the source for the two controls you added to your form.

<div>

<asp:ObjectDataSource ID=”ObjectDataSource1” runat=”server” OldValuesParameterFormatString=”original_{0}”

SelectMethod=”GetPlayers”

TypeName=”wroxunitedTableAdapters.PlayersTableAdapter”>

</asp:ObjectDataSource>

</div>

<asp:GridView ID=”GridView1” runat=”server” AutoGenerateColumns=”False” DataKeyNames=”PlayerID”

DataSourceID=”ObjectDataSource1”>

<Columns>

<asp:BoundField DataField=”PlayerID” HeaderText=”PlayerID” InsertVisible=”False”

ReadOnly=”True” SortExpression=”PlayerID” /> <asp:BoundField DataField=”FirstName” HeaderText=”FirstName”

SortExpression=”FirstName” />

366

Componentization

<asp:BoundField DataField=”LastName” HeaderText=”LastName” SortExpression=”LastName” />

<asp:BoundField DataField=”Position” HeaderText=”Position” SortExpression=”Position” />

<asp:BoundField DataField=”DateJoined” HeaderText=”DateJoined”

SortExpression=”DateJoined” />

<asp:BoundField DataField=”DateLeft” HeaderText=”DateLeft” SortExpression=”DateLeft” />

</Columns>

</asp:GridView>

The GridView control binds each of the fields in the dataset to a column in a table on the display. The ObjectDataSource takes five attributes. The ID and runat attributes are standard, the

OldValuesParameterFormatString is set to the original setting, the SelectMethod attribute specifies the name of the actual method, and the TypeName specifies the PlayersTableAdapter. These are all the instructions needed to be able to bind the return PlayersTable to the GridView control. The final display looks the same as a normal GridView control; it’s only the plumbing underneath that has routed your data from the ObjectDataSource control that is different.

The Wrox United ObjectDataSource

This data so far has been static; so as we mentioned previously, in this next Try It Out you go one further and use the ObjectDataSource control to be able to edit and update your squad’s details. In the Admin section of the Wrox United site there is a page called EditSquad.aspx, which is used to change the players’ details. However, it uses the SqlDataSource control for the details. This can be replaced with an ObjectDataSource control. It has the insert, update, select, and delete methods to map neatly to the methods in a simple class.

Try It Out

The Wrox United ObjectDataSource

1.Open the Wrox United application from the chapter samples (C:\BegASPNET2\Chapters\ Begin\Chapter10\WroxUnited) in Visual Web Developer.

2.Right-click the App_Code folder and select Add New Item from the list.

3.From the Visual Studio installed templates, click DataSet.

4.Rename the DataSet wroxunited.xsd and click Add.

5.Next, VWD will start the TableAdapter Configuration Wizard. Be patient here, because this one really does take a while to kick in.

6.When it finally arrives, select wroxunited (Web.config), and click Next.

7.Next, you get a page where you can choose to use SQL statements or stored procedures. Select the Use SQL statements radio button and click Next.

8.On the next wizard screen you can define the SQL statement. Type the following SQL statement into the “What data should be loaded into the table” area of the dialog:

367

Chapter 10

SELECT PlayerID, FirstName, LastName, Position, PictureURL, DateJoined, DateLeft

FROM Players

WHERE PlayerID = @PlayerID

9.After entering the SQL statement, click Next. You can now define which methods the component will expose. Uncheck the Fill a DataTable checkbox and make sure that Return a DataTable checkbox is checked. In the Method name box, type GetPlayers. This method is used later to retrieve the data. Make sure the final checkbox “Create methods to send update directly to the database” box is checked.

10.Click Next and the click Finish, save the data component, and close the component designer.

11.Select Build Build Web Site to compile the component.

12.Open the Admin folder of WroxUnited and open the file EditSquad.aspx.

13.In Design View scroll down, select the second SqlDataSource control (shown in Figure 10-15),

DetailsDataSource, and delete it.

Figure 10-15

368