
Beginning ASP.NET 2.0 With CSharp (2006) [eng]
.pdf
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
358

Componentization
advantages of doing this are 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 they shouldn’t be interfering there at all. So this brings you to the end of your 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 enables 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. You’re actually going to do two examples to show it in action. In the first example, you’ll see how to create a data component to return a list of players from the Players table. This Try It Out is split into two sections: the first section where you create the ObjectDataSource itself and the second where you bind the ObjectDataSource control to a GridView control. The resulting output will be completely non-editable. In the second example, you’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. You’ll create and bind the data component in this same example that 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.
Start by creating the data component for the 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.VWD starts the TableAdapter Configuration Wizard. (Be patient here, because this one really does take a while to kick in.) When the wizard finally arrives, select ConnectionString (Web.config) from the drop-down list (see Figure 10-8) and click Next.
359

Chapter 10
Figure 10-8
7.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
360

Componentization
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 box:
SELECT PlayerID, FirstName, LastName, Position, DateJoined, DateLeft FROM Players
9.After entering the SQL statement, click Next. You can now define which methods the component will expose. Uncheck the Fill a DataTable check box and make sure that the Return a DataTable check box 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 check box.
Figure 10-10
10.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
11.Save the data component and close the component designer.
12.Select Build Build Web Site to compile the component. (Note that this won’t produce anything viewable.)
361

Chapter 10
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 by which you want to be able to call this component.
Thenext 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 in 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 box 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 it and click Next.
Figure 10-12
6.On the next screen (shown in Figure 10-13), under the Select tab in the Choose a method dropdown box, the GetPlayers(), returns PlayersDataTable method is displayed. Select it and click Finish (the other methods are automatically picked for you).
362

Componentization
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.
Figure 10-14 |
363 |
|

Chapter 10
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=”odsTableAdapters.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” />
<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 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 insert, update, select, and delete methods that map neatly to the methods in a simple class.
364

Componentization
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.VWD starts the TableAdapter Configuration Wizard. (As before, be patient here.) When the wizard finally arrives, select wroxunited (Web.config) and click Next.
6.When you get the page where you can choose to use SQL statements or stored procedures. select the Use SQL statements radio button and click Next.
7.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 box:
SELECT PlayerID, FirstName, LastName, Position, PictureURL, DateJoined, DateLeft
FROM Players
WHERE PlayerID = @PlayerID
8.After entering the SQL statement, click Next. You can now define which methods the component will expose. Uncheck the Fill a DataTable check box and make sure that Return a DataTable check box is checked. In the Method name box, type GetPlayers. This method is used later to retrieve the data. Make sure the final check box, “Create methods to send update directly to the database,” is checked.
9.Click Next and then click Finish. Save the data component, and close the component designer.
10.Select Build Build Web Site to compile the component.
11.Open the Admin folder of WroxUnited and open the EditSquad.aspx file.
12.In Design View, scroll down, select the second SqlDataSource control, DetailsDataSource (shown in Figure 10-15), and delete it.
13.From the Data Section of the Toolbox, drag an ObjectDataSource control where the
SqlDataSource used to be.
14.Click the black arrow at the top right of the ObjectDataSource control, and from the Common Tasks menu, select Configure Data Source.
15.In the opening dialog box, select wroxunitedTableAdapters.PlayersTableAdapter and click Next.
16.In the Select tab, select the GetPlayers(Int32 PlayerID), returns PlayersDataTable method from the drop-down list box and click Next.
17.In the Define Parameters dialog box, select Control from the Parameter Source drop-down list box. Select GridView1 in Control view. The parameters on the left of the dialog box will now show GridView.SelectedValue. Click Finish.
365

Chapter 10
Figure 10-15
18.Right-click the ObjectDataSource control in Design View and select Properties.
19.In the Properties window, change the (ID) property so that it reads “DetailsDataSource”.
20.Open EditSquad.aspx.cs and amend the code in the procedure parameters to read as follows in the three subs:
protected void DetailsDataSource_Updated(object sender , System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs e)
{
...
}
protected void DetailsDataSource_Inserted(object sender , System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs e)
...
}
protected void DetailsDataSource_Deleting(object sender , As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs e)
{
...
}
366

Componentization
21.Save and close the file.
22.Run the application, log in as an administrator (dave\dave@123), and navigate to the EditSquad.aspx page. It works in the same way as before except that you are now using an
ObjectDataSource control.
How It Works
You haven’t changed much between this and the previous example. You built a data component, and you then added an ObjectDataSource control into the EditSquad.aspx page. You added methods for the Update, Insert, and Delete methods via the wizard. The code that provided your functionality in the classes was already in existence — all you had to do was change the references from the SqlDataSource control to the ObjectDataSource control. Then you ran it, and the WroxUnited application was able to use the ObjectDataSource instead.
User Controls
Your final problem is that of making your code easy to reuse, and this is addressed by user controls. Again, these existed in ASP.NET 1.x, but this is something that also has been improved upon in ASP.NET 2.0. So what are user controls? Well in a nutshell, user controls are reusable Web Forms. They’ve been through several name changes and evolutions from scriptlets to pagelets, before arriving at user controls. They can be thought of as mini-scripts, mini-pages, or pages within your pages, but however you choose to think of them, the key is that they can be called up as many times as you need them.
If you browse the Wrox United site, you can see several examples of user controls, and one, the News control, is visible on the front page. In fact, if you look at the front page (shown in Figure 10-16), it is a multitude of components garnered from different sources.
The News control is a user control, the Login control is an ASP.NET control, the shopping cart is a link to a user control, and the menu is derived from the site master, which itself is an ASP.NET control. So the entire site front page and design is reusable. If you click the Shopping Cart link, you will see the second user control, shown in Figure 10-17.
And there are a couple more user controls in the administrative section of the site too, but you get the idea that these controls can be used in multiple pages, or called from different places, and rather than having to cut and paste the code individually each time, you can just call on this one section of code over and over again. One question you might have is how do they differ from the normal ASP.NET server controls, such as the TextBox control or the Login control that you looked at earlier?
Very little is the answer. The main difference is that you have to provide the code behind the control yourself, whereas ASP.NET server controls come fully functional out of the box. You can add properties to user controls and set them as attributes, just like you would with a normal ASP.NET server control.
367