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

ASP.NET 4 Unleased - p 41 potx

10 206 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 823,43 KB

Nội dung

ptg 374 CHAPTER 8 Overview of Data Access When you click Add, Visual Web Developer warns you that it needs to create the App_Data folder (if the folder doesn’t already exist). The MyLocalData.mdf file will be added to this folder. Click OK to create the new folder. You can connect to a Local database named MyLocalData.mdf by using the following connection string: Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|MyLocalData.mdf; Integrated Security=True;User Instance=True When you connect to the MyLocalData.mdf file, the database is attached automatically to Microsoft SQL Server Express. The connection string includes an AttachDbFilename parameter. This parameter represents the physical path to a database file (.mdf file). The keyword |DataDirectory| is used in the path. The |DataDirectory| keyword represents a website’s App_Data folder. Instead of using the |DataDirectory| keyword, you could supply the entire physical path to a database file. The advantage of using the |DataDirectory| keyword is that you can move your web application easily to a new location without needing to change the connection string. The connection string also includes a User Instance parameter. Creating a User Instance connection enables you to connect to a Local database without using an Administrator account. Because the ASPNET account is not an Administrator account, you need to add this parameter to use Local databases from ASP.NET pages. Including the User Instance parameter in a connection string causes a separate user instance of SQL Server to execute with the security context of the user. The first time a user creates a User Instance connection, copies of the system databases are copied to a user’s application data folder located at the following path: C:\Users\[Username]\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS A separate set of system databases is created for each user. NOTE By default, when a page is served from Internet Information Server, the page executes in the security context of either the ASPNET or Network Service account. When a page is served from the web server included in Visual Web Developer, the page executes in the security context of the current user. One of the primary advantages of using a Local database rather than a Server database is that a Local database can be moved easily to a new location. If you email a Local database file (the .mdf file stored in the App_Data folder) to a friend, your friend can start using the database immediately. The only requirement is that your friend has SQL Server Express installed on a computer. From the Library of Wow! eBook ptg 375 Sample Database-Driven Web Application 8 Sample Database-Driven Web Application The following chapters get into all the gritty details of the Data controls. Before you get lost in the details, however, I want to provide you with a sample of a data-driven web application. I want to provide you with a real-world application that illustrates what can be built with the Data controls. In this section, a complete Employee Directory application is built, which supports displaying, adding, editing, and deleting employee information. The sample application includes all the necessary form field validation. One of the amazing things about ASP.NET 4 Framework is how much the Framework simplifies data access. The sample application consists of a single page that contains little code. Writing the same application with ASP.NET 1.x Framework would require pages of code. (I won’t even mention how much code it would require to write the same applica- tion in ASP Classic.) Because the Employee Directory application includes all the required validation code, the page is a little too long to include in the pages of this book. However, it is included on the book’s website. Open the page named EmployeeDirectory.aspx. After you open the EmployeeDirectory.aspx page in your browser, you see a list of employees. This list is rendered by a GridView control (see Figure 8.18). FIGURE 8.18 Displaying a list of employees with the GridView control. From the Library of Wow! eBook ptg 376 CHAPTER 8 Overview of Data Access Next to each employee, there is a Delete link and a Details link. If you click Delete, the selected employee is deleted from the database. A client-side confirmation dialog box appears when you click the Delete link (see Figure 8.19). This dialog box is added to each of the Delete links in the grdEmployees_RowCreated() method. This method is called automatically by the GridView control as the GridView creates each row. FIGURE 8.19 Deleting employee information. If you click the Details link, a window appears that displays detailed information for the Employee (see Figure 8.20). The detailed information is rendered by a FormView control. The window that appears is created with an absolutely positioned <div> tag. If you click Edit when viewing a employee’s details, you can edit the employee record. The edit form is contained in the FormView control’s EditItemTemplate. Each of the form fields is associated with a RequiredFieldValidator control. Finally, you can add new employees to the directory by clicking the Add Employee button. The form that appears is also rendered by a FormView control (see Figure 8.21). WEB STANDARDS NOTE The Employee Directory application works great in Internet Explorer 6+, Firefox 1.0+, and Opera 8.0+. The only feature of the application that breaks Web standards is the use of the Drop Shadow filter around the pop-up window. The Drop Shadow effect works only in Internet Explorer. From the Library of Wow! eBook ptg 377 Sample Database-Driven Web Application 8 FIGURE 8.20 Displaying employee details. FIGURE 8.21 Adding a new employee. From the Library of Wow! eBook ptg 378 CHAPTER 8 Overview of Data Access Summary In this chapter, you were provided with an overview of the Data controls included in the ASP.NET 4 Framework. You learned how to use the DataBound controls to render the user interface for working with data. You also were provided with an introduction to the DataSource controls, which can be used to represent different types of data such as data- base data and XML data. You also learned about two important features of the DataBound controls. You learned how to use Templates and databinding expressions. You learned about the difference between one-way databinding and two-way databinding expressions. Next, you were provided with an overview of SQL Server 2008 Express. You learned how to create a SQL Server Express database. You also learned how to create both Server and Local databases. Finally, the Data controls were used to build a sample application: the Employee Directory application. You learned how to use the controls to build an application that enables you to list, edit, insert, and delete database records. From the Library of Wow! eBook ptg CHAPTER 9 Using the SqlDataSource Control IN THIS CHAPTER . Creating Database Connections . Executing Database Commands . Using ASP.NET Parameters with the SqlDataSource Control . Programmatically Executing SqlDataSource Commands . Caching Database Data with the SqlDataSource Control . Summary The SqlDataSource control enables you to quickly and easily represent a SQL database in a web page. In many cases, you can take advantage of the SqlDataSource control to write a database-driven web page without writing a single line of code. You use the SqlDataSource control to represent a connec- tion and set of commands that can be executed against a SQL database. You can use the SqlDataSource control when working with Microsoft SQL Server, Microsoft SQL Server Express, Microsoft Access, Oracle, DB2, MySQL, or just about any other SQL relational database ever created by man. NOTE Although you can use the SqlDataSource control when working with Microsoft Access, the ASP.NET Framework does include the AccessDataSource con- trol, which was designed specifically for Microsoft Access. Because using Microsoft Access for a website is not recommended, this book doesn’t discuss the AccessDataSource control. The SqlDataSource control is built on top of ADO.NET. Under the covers, the SqlDataSource uses ADO.NET objects such as the DataSet, DataReader, and Command objects. Because the SqlDataSource control is a control, it enables you to use these ADO.NET objects declaratively rather than programmatically. From the Library of Wow! eBook ptg 380 CHAPTER 9 Using the SqlDataSource Control The SqlDataSource control is a nonvisual control—it doesn’t render anything. You use the SqlDataSource control with other controls, such as the GridView or FormView controls, to display and edit database data. The SqlDataSource control can also be used to issue SQL commands against a database programmatically. NOTE The SqlDataSource control is not an appropriate control to use when building more complicated multitier applications. The SqlDataSource control forces you to mix your data access layer with your user interface layer. If you want to build a more cleanly architected multi-tier application, you should use the ObjectDataSource control to represent your database data. The ObjectDataSource is discussed in detail in Chapter 18, “Using the ObjectDataSource Control.” In this chapter, you learn how to represent connections and commands with the SqlDataSource control. You also learn how to use different types of parameters when executing commands. Finally, you learn how to improve the performance of your database-driven applications by taking advantage of the SqlDataSource control’s support for caching database data. Creating Database Connections You can use the SqlDataSource control to connect to just about any SQL relational data- base server. In this section, you learn how to connect to Microsoft SQL Server and other databases such as Oracle. You also learn how you can store the database connection string used by SqlDataSource securely in your web configuration files. Connecting to Microsoft SQL Server By default, the SqlDataSource control is configured to connect to Microsoft SQL Server version 7.0 or higher. The default provider used by the SqlDataSource control is the ADO.NET provider for Microsoft SQL Server. You represent a database connection string with the SqlDataSource control’s ConnectionString property. For example, the page in Listing 9.1 includes a SqlDataSource control that connects to a local SQL Server 2008 database (see Figure 9.1). From the Library of Wow! eBook ptg 381 Creating Database Connections LISTING 9.1 ShowLocalConnection.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>Show Local Connection</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:GridView id=”grdMovies” DataSourceID=”srcMovies” Runat=”server” /> <asp:SqlDataSource id=”srcMovies” SelectCommand=”SELECT * FROM Movies” ConnectionString=”Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|MyDatabase.mdf; 9 FIGURE 9.1 Displaying the Movies database table. From the Library of Wow! eBook ptg 382 CHAPTER 9 Using the SqlDataSource Control Integrated Security=True;User Instance=True” Runat=”server” /> </div> </form> </body> </html> In Listing 9.1, the SqlDataSource control uses the following connection string: Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|MyDatabase.mdf; Integrated Security=True;User Instance=True This connection string connects to an instance of SQL Server Express located on the local machine and a database file named MyDatabase.mdf. The connection string uses Integrated Security (a Trusted Connection) to connect to the local database. You can use the following connection string to connect to a database located on a remote server. Data Source=DataServer;Initial Catalog=Northwind; User ID=webuser;Password=secret This database connection string connects to a SQL Server database located on a remote machine named DataServer. The connection string connects to a database named Northwind. This second connection string uses SQL Standard Security instead of Integrated Security. It contains a user ID and password associated with a SQL Server login. WARNING For security reasons, you should never include a connection string that contains securi- ty credentials in an ASP.NET page. Theoretically, no one should see the source of an ASP.NET page. However, Microsoft does not have a perfect track record. Later in this section, you learn how to store connection strings in the web configuration file (and encrypt them). The .NET Framework includes a utility class, named the SqlConnectionBuilder class, that you can use when working with SQL connection strings. This class automatically converts any connection string into a canonical representation. It also exposes properties for extracting and modifying individual connection string parameters, such as the Password parameters. From the Library of Wow! eBook ptg 383 Creating Database Connections For example, the page in Listing 9.2 automatically converts any connection string into its canonical representation (see Figure 9.2). 9 LISTING 9.2 SqlConnectionStringBuilder.aspx <%@ Page Language=”C#” %> <%@ Import Namespace=”System.Data.SqlClient” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”> <script runat=”server”> protected void btnConvert_Click(object sender, EventArgs e) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(txtConnectionString.Text); lblResult.Text = builder.ConnectionString; } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>SQL Connection String Builder</title> </head> FIGURE 9.2 Converting a connection string. From the Library of Wow! eBook . about ASP. NET 4 Framework is how much the Framework simplifies data access. The sample application consists of a single page that contains little code. Writing the same application with ASP. NET. controls. In this section, a complete Employee Directory application is built, which supports displaying, adding, editing, and deleting employee information. The sample application includes all the. application that breaks Web standards is the use of the Drop Shadow filter around the pop-up window. The Drop Shadow effect works only in Internet Explorer. From the Library of Wow! eBook ptg 377 Sample

Ngày đăng: 06/07/2014, 18:20

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN