Beginning Web Development, Silverlight, and ASP.NET AJAX From Novice to Professional phần 3 pps

44 397 0
Beginning Web Development, Silverlight, and ASP.NET AJAX From Novice to Professional phần 3 pps

Đ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

9594CH03.qxd 1/2/08 2:57 PM Page 68 Data Binding with ASP.NET Most applications use some form of data store, with the application itself being a means to store, retrieve, manipulate, and view data. These applications might use a SQL Server 2005 database, a storage area network, or even a simple XML file. Web applications are no exception, and typically these applications are termed data-driven applications. When it comes to retrieving and representing data, a myriad of options are available; over time, the technology has evolved dramatically. The reason for this is that the code needed to access data and the engines that run the data itself tend to be resource heavy, and in situations such as on the Web where they may be used in clustered environments (i.e., the same application running on a number of machines) and serving millions of users, they can be expensive to maintain. As a result, the technology that developers use to cre- ate data-driven applications has evolved rapidly, driven by the needs of scaling to large audiences. .NET provides a data programming technology for you to use in your applications. It is called ADO.NET. It consists of a number of managed classes that enable your applica- tions to connect to data sources, execute commands, and manage disconnected data. In this chapter, you’ll look at the architecture of ADO.NET and how it works to bring data to your application. You’ll look into the SQL Server 2005 Express edition, a free version of the industry- leading enterprise database software from Microsoft, as well as a sample database, AdventureWorks, that is used to demonstrate many of its features. You’ll wrap the chapter up with a tour through some of the server controls that can be used to provide data awareness to your web application through data binding. What Is ADO.NET? Scalability is typically achieved by breaking an application into functional tiers. As I men- tioned in the previous chapter, keeping state between tiers has a high cost when it comes to scalability, performance, and security. Data-aware applications are no exception. ASP.NET offers view state as a great alternative to maintaining control state between the browser and server to provide both a nice programming interface and control state man- agement with minimum resource consumption. When writing data applications, the cost 69 CHAPTER 4 9594CH04.qxd 1/22/08 10:17 AM Page 69 of maintaining state between the tiers of your application can be much higher, as you may be passing large amounts of data (sometimes referred to as data sets) between them. Thus, ADO.NET offers a disconnected model that enables you to access data from another tier, disconnect from that tier (thus breaking state), and access that data locally. To prevent data from being corrupted, ADO.NET provides the means for syncing back up with the data store when your transaction is complete, as well as locking mechanisms to prevent other processes from affecting the data while your application is holding it in a disconnected state. At the heart of the disconnected model is XML. ADO.NET was designed with the XML classes of the .NET Framework in mind, and at the core of this is the DataSet object, which you’ll undoubtedly encounter if you continue writing ADO.NET-based applica- tions. (It’s also used under the covers when controls are automatically bound to a database , although that’s not obvious at a casual glance.) Using ADO.NET You use a .NET data provider to connect to the data store. A provider is one or more classes that give you pr ogrammatic access to a database, providing methods that enable you to read or update data stored in the supported data store. The main classes that you’ll use when using a data provider to connect to databases are as follows: Connection: As its name suggests, the Connection class is used to make and manage the connection with the database. Command: You use Command to create and execute Structured Query Language (SQL) statements against your database, or to access stored procedures already on the database and execute them. DataReader: When you want to access data in a read-only manner, moving forward through the data as you read, this class provides a lightweight, fast component that achieves this. DataAdapter: The DataAdapter class is used to facilitate the communication between the disconnected DataSet and the data store. It fills the DataSet with data and pro- vides the methods to apply changes to the data stored within the data store based on any modifications made within the (disconnected) DataSet. DataSet: The DataSet is a disconnected representation of all or part of a database. It is much more sophisticated than something like a recordset or table because it can support a collection of tables, relationships, constraints, and more. ADO .NET supplies y ou with a number of built-in pr o viders, including a SQL Server pr o vider that is optimiz ed for SQL S erver. This includes all of the preceding classes CHAPTER 4 ■ DATA BINDING WITH ASP.NET70 9594CH04.qxd 1/22/08 10:17 AM Page 70 (Connection, Command, etc.) that are written specifically for this database. In addition to this, there is also an Object Linking and Embedding for Databases (OLEDB) provider and an Open Database Connectivity (ODBC) provider, which are written to access any data- base that provides OLEDB or ODBC databases, respectively. Although these aren’t optimized for a database such as SQL Server, they will still work. For older versions of SQL Server that do not support the ADO.NET provider (earlier than 7.0), they provide a viable option. The built-in set of providers is rounded out with an Oracle provider, which is opti- mized for Oracle databases. The recommendation if you are using Oracle or SQL Server is to use their dedicated pr oviders, due to the optimization inherent in them. Should this not work, OLEDB is rec- ommended, and then the ODBC provider as a final fallback option. You are, of course, not limited to these providers, and a third-party ecosystem of providers around databases such as MySQL and PostGreSQL has evolved. Take note that these providers form dependencies that you’ll need to account for when you deploy your application. Despite the fact that you use different providers for different databases or versions of databases, the API has been carefully designed to avoid fragmentation. Each provider is built upon a standard set of interfaces that ensure that the method signatures for stan- dard operations such as open and close are preserved. Because of this, your application data access code is buffered from change if you switch databases. We’ll go into ADO.NET programming a little later in this chapter, but first, it’s a good idea to get a copy of SQL Server. If you don’t have one already, the Express edition can be downloaded from MSDN at http://msdn.microsoft.com/vstudio/express/sql. We’ll explore this in the next few sections before delving back into ADO.NET development to round out the chapter. Note that if y ou are using Windows Vista, you should find Service Pack 2 (SP2) for SQL Server Express and then do wnload and install that. SP2 is available from the Visual Studio Express download site at http://msdn.microsoft.com/vstudio/express/ sql/register/default.aspx. SQL Server 2005 Express If you’ve developed Windows applications before, you may have encountered a “mini” desktop database called Microsoft SQL Server Desktop Engine 2000 (MSDE). SQL Server 2005 Express edition is the next version of this and is free to download, redistribute, and embed in y our applications . It’s a great way to get familiar with SQL Server because it can be used with tools such as SQL S er ver Management Studio, which may be downloaded and installed fr om the same site as SQL S erver Express. This tool is also used in the Enter- pr ise editions . In this section, you’ll look at downloading, installing, and configuring SQL S erver Express for your applications. CHAPTER 4 ■ DATA BINDING WITH ASP.NET 71 9594CH04.qxd 1/22/08 10:17 AM Page 71 Downloading and Installing SQL Server 2005 Express There are a number of different options presented to you when you want to download SQL Server Express: Core SQL Server Express: This provides the basic runtime engine for SQL Server. It can be embedded within Microsoft Visual Studio 2005 (but not the Express editions), is free to distribute, and can be seamlessly upgraded to Professional or Enterprise editions of SQL Server. SQL Server Management Studio Express: This is the tool that you can use to manage instances of SQL Server or SQL Server Express. It is a recommended tool if you are using Express editions of Visual Studio, or if you want to learn about administration of the Professional versions of SQL Server. Please note that this is downloaded separately. SQL Server Express with Advanced Services: This adds features to Core SQL Server Express, including Management Studio, reporting services, and full-text search. SQL Server Express Edition Toolkit: This adds tools, including a report creator for reporting services, the business intelligence development studio for building stored pr ocedures and other database-related functionality, and the SQL Server software development kit (SDK). In this chapter, we’ll be looking at SQL Server 2005 Express with Advanced Services, which provides a single download that gives you SQL Server and Management Studio. Starting the Install Once you’ve downloaded SQL Server 2005 Express with Advanced Services (available at www.microsoft.com/express/sql/default.aspx), launch it to get the installer. The first screen that you’ll see is the End User License Agreement (EULA), which you will need to accept to continue (see Figure 4-1). CHAPTER 4 ■ DATA BINDING WITH ASP.NET72 9594CH04.qxd 1/22/08 10:17 AM Page 72 Figure 4-1. SQL Server Express EULA Click Next to continue the installation, and the installer will install all the necessary setup files. Once this is complete, the installer will scan your system for prerequisites, and should you have them all installed, it will launch (see Figure 4-2). If there are any installation problems, a different dialog will show you what they are. Figure 4-2. Beginning the installation CHAPTER 4 ■ DATA BINDING WITH ASP.NET 73 9594CH04.qxd 1/22/08 10:17 AM Page 73 Clicking Next will take you to the System Configuration Check, at which point your system will be scanned for the required components. Should any of them be missing, you will receive a warning or an error message, and the Message column will instruct you what to do. Figure 4-3 shows an example in which the Internet Information Services (IIS) feature requirement hasn’t been met; it isn’t a critical problem, just a warning. This is one of the Windows Vista incompatibilities mentioned earlier—the current version of SQL Server Express doesn’t recognize IIS 7. Figure 4-3. System Configuration Check When you get to the Registration Information screen (see Figure 4-4), remember to uncheck the box that reads “Hide advanced configuration options.” CHAPTER 4 ■ DATA BINDING WITH ASP.NET74 9594CH04.qxd 1/22/08 10:17 AM Page 74 Figure 4-4. Registration information The next screen is where you configure what you want to install. In this case, you should make sure that you install at least Database Services and Management Studio Express (see Figure 4-5). Figure 4-5. F eatur e S election scr een CHAPTER 4 ■ DATA BINDING WITH ASP.NET 75 9594CH04.qxd 1/22/08 10:17 AM Page 75 Your next step is to set the authentication mode for SQL Server (see Figure 4-6). There are two ways you can log into the database. You can use Windows authentication only when your Windows sign-on credentials are used to access the database, and you can use Mixed Mode authentication when SQL Server has its own set of credentials. Windows authentication is considered the most secure and direct method of authen- tication, and for this book, I recommend that you use it. You also have the option of using Mixed Mode authentication for greater flexibility. Should you do this, you will have to configure the sa login, which is the credential set for the SQL Server administrator. Figure 4-6. Configuring the SQL Server authentication mode The next screen allows you to set the configuration options (see Figure 4-7). There ar e two main options that you can set. The first is Enable User Instances, which if set will allo w users that do not hav e administr ative access to run separate instances of the SQL S er ver Express engine. The second, if set, will add the user that is installing the database as a SQL S er ver administrator. You can see this in Figure 4-7. CHAPTER 4 ■ DATA BINDING WITH ASP.NET76 9594CH04.qxd 1/22/08 10:17 AM Page 76 Figure 4-7. Configuration options The final step is an option screen that allows you to configure feedback settings that, if set, will allow SQL Server to send errors back to Microsoft, allowing them to improve the product. This is shown in Figure 4-8. Figure 4-8. E rr or and U sage R epor t S ettings scr een CHAPTER 4 ■ DATA BINDING WITH ASP.NET 77 9594CH04.qxd 1/22/08 10:17 AM Page 77 [...]... your database structure and contents, enabling you to create and delete databases, insert and retrieve data, and manipulate table structures, among other things A command is implemented via the SqlCommand class and controlled using the SqlCommand.CommandType and SqlCommand.CommandText properties, which are often used in tandem If you set the CommandType to CommandType.Text, the CommandText property (a... code to access the addresses for postal code 98011 in the AdventureWorks database Listing 4-1 Using Connection, Command, and Reader to Access Data using using using using using using using using using using using System; System.Data; System.Configuration; System .Web; System .Web. Security; System .Web. UI; System .Web. UI.WebControls; System .Web. UI.WebControls.WebParts; System .Web. UI.HtmlControls; System .Web. Configuration;... improvements (see Figure 4 -33 ) Figure 4 -33 Running the application with the revised DataList control 9594CH04.qxd 1/22/08 10:17 AM Page 1 03 CHAPTER 4 s DATA BINDING WITH ASP.NET Summary This chapter gave you a whirlwind tour of data in ASP.NET and showed how your web applications can be used to access data You looked at ADO.NET and how it works, as well as how to download and install SQL Server 2005... you started writing ADO.NET code to access and read from the database Then, you wrapped up with a tutorial on how to use the Visual Studio designers and tools to create connections to the database, and bind the GridView and DataList controls to present your data, which resulted in a pretty decent web- based data display application, complete with styling, selection, and pagination without writing a... Server database, the next step is to learn more about ADO.NET and start building some applications designed to work with databases and data You’ll do this in two steps First, you’ll learn how to use the coding environment to create connections to the data and to retrieve data sets that you’ll manipulate, and then you’ll start looking at the graphical user interface (GUI) tools that provide this for you,... BINDING WITH ASP.NET Figure 4-18 Using a parameterized query Data Binding with Server Controls You’ve seen in the previous sections how ASP.NET and ADO.NET can be used to connect to databases and manipulate the data therein through connections, commands, and readers However, most modern applications require flexible, graphical access to the same data As a developer, you aren’t going to want to develop... columns—AddressLine1 and PostalCode—which have been automatically added to the GridView If you only want to show the AddressLine1 column values, you can easily do this by selecting the PostalCode column and deleting it from this dialog box (see Figure 4-26) Alternatively, you may want to be able to access the column from code, but not show it to the user In this case, you can set the column’s Visible property to False... that you want to execute If the type is CommandType StoredProcedure, the CommandText should contain the name of the stored procedure to execute Finally, if the type is CommandType.Table, the command text should contain the name 9594CH04.qxd 1/22/08 10:17 AM Page 87 CHAPTER 4 s DATA BINDING WITH ASP.NET of a table in your database Executing this type of command will return all records stored in that... sqlComm.CommandType = CommandType.Text; sqlComm.CommandText = "SELECT AddressLine1 FROM Person.Address " + "WHERE (PostalCode = N'98011')"; Executing the Command Now that you have your command, you are going to want to execute it to do anything meaningful There are four different methods for executing an ADO.NET command: ExecuteNonQuery: This is used to execute a query for which you do not want to return a result... using Windows Vista, the operating system will prevent you from writing to the Data directory for security reasons, and this operation will fail You will need to navigate to the MDF and LDF files for AdventureWorks from within Windows Explorer and use the security settings in the Properties dialog box Add permissions for the SQL Server processes to have full control over these files Once you’ve connected . class and contr olled using the SqlCommand.CommandType and SqlCommand.CommandText pr oper ties , which are often used in tandem. I f y ou set the CommandType to CommandType.Text, the CommandText. from wr iting to the Data dir ectory for security reasons, and this operation will fail. You will need to navigate to the MDF and LDF files for A dventureWorks from within Windows Explorer and. applica- tions to connect to data sources, execute commands, and manage disconnected data. In this chapter, you’ll look at the architecture of ADO .NET and how it works to bring data to your application. You’ll

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

Mục lục

  • Data Binding with ASP.NET

    • What Is ADO.NET?

      • Using ADO.NET

      • SQL Server 2005 Express

        • Downloading and Installing SQL Server 2005 Express

        • Starting the Install

        • Using SQL Server Management Studio Express

        • Installing the AdventureWorks Database

        • Using ADO.NET to Build Data-Driven Applications

          • The Connection Class and Connection Strings

            • Visually Designing Your Connection String

            • Accessing a Connection

            • Using Commands

              • Executing the Command

              • Reading the Data

              • Using Parameters in Commands

              • Data Binding with Server Controls

                • Using the SQLDataSource Control

                • Using the GridView Control

                • Using the DataList Control

                • Summary

                • ASP.NET Web Services

                  • Web Services Architecture

                  • Building a Web Service in Visual Studio

                    • The ASMX and Code-Behind Files

                    • Running Your Web Service

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

Tài liệu liên quan