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

Beginning asp net 2.0 with c phần 4 ppsx

77 327 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

Định dạng
Số trang 77
Dung lượng 1,88 MB

Nội dung

else { startYear = today.Year - 1; endYear = today.Year; } Next you create the actual start and end dates of the season, using the start and end year already set: seasonStart = new DateTime(startYear, 8, 20); // 20th August seasonEnd = new DateTime(endYear, 5, 31); // 31st May Now you check to see if the current date falls within the season start and end dates. If it does, you set the Cancel property of the parameter e to true, so when the event procedure ends the event action (the delete) will be cancelled. You also display a message to tell the user that players cannot be deleted dur- ing the season: if (today >= seasonStart && today <= seasonEnd) { e.Cancel = true; Message.Text = “Cannot delete players during the season”; } If you are outside of the season, players can be deleted, so you simply clear any message and rebind the grid (so that the deleted player doesn’t still show in the grid). Because you haven’t set the Cancel prop- erty of parameter e to true (it is false by default), the action will take place, and the player will be deleted: { GridView1.DataBind(); Message.Text = “”; } So what you’ve seen here is that some events can be cancelled, which allows you to build logic into your applications, enabling you to control the actions that are run. This also means that events that you think will run might not. For example, it was mentioned earlier that some of these events are paired. So, as well as the Deleting event, there is a Deleted event, and if you cancel the Deleting event the Deleted event isn’t run. The logic of this is shown in Figure 6-21. This process is also the same for inserted and updated items, where the Inserting and Updating event procedures are used. In all three cases you can set the Cancel property of the parameter to true to can- cel the event. 199 Events and Code 09_042583 ch06.qxd 4/4/06 2:44 PM Page 199 Figure 6-21 Global Events So far in this chapter you’ve seen that events are raised by controls or by pages, but there is a third type of event — an application event. Application events are raised by ASP.NET in response to certain condi- tions, and these are stored in the Global Application Class, global.asax, a code-only file. The global.asax page has several events: ❑ Application_Start, which is raised when the application first starts. This is when the first user accesses the site and should be used to set any initial start conditions. FirstName LastName Position PictureURL Chris Christopher Left Back aaronson.jpg Date Joined Date Left Edit Delete New SqlDataSource - DetailsDataSource Deleting Is deletion Allowed? Event Cancelled Event raised Deleted Yes No Event Runs 200 Chapter 6 09_042583 ch06.qxd 4/4/06 2:44 PM Page 200 ❑ Application_End, which is raised when the application stops. ❑ Session_Start, which is raised when a user starts a session. This is when the user starts accessing the site for the first time, and includes the time when a user closes the browser win- dow and opens it again. ❑ Session_End, which is raised when a user session ends. This isn’t when the browser window is closed, because sessions have a timeout — if there is no user activity within that time, the ses- sion ends. ❑ Application_Error, which is raised when an unhandled error occurs. ❑ Profile_OnMigrateAnonymous, which is raised when an anonymous user logs in, and allows migration of any Profile properties. You can create a Global Application Class in the same way as adding normal Web Forms, and when cre- ated, the first four events in the preceding list will be created for you. They’ll have no code, but will be ready for you to add code if you need it. In the Wrox United application, none of the first four events are used, but the latter two are. The Application_Error event is covered in Chapter 15, which looks at error handling, and the Profile_OnMigrateAnonymous event is covered in Chapter 11, which looks at the Profile. Summary This chapter covered a lot about events, and you’ve seen that they can be raised under a number of dif- ferent circumstances. First you looked at the ASP.NET page itself, where an event is raised when the page is loaded, which allows you to take some action before anything is shown to the user. Additionally, this chapter examined the following topics: ❑ The ASP.NET page has the IsPostback property that allows you to identify whether this is the first time the page has been displayed, or whether the user has clicked a button. ❑ Button controls, where an event is raised when the user clicks the button. You saw that similar types of controls (the Button and ImageButton controls) have similar events (the Click event). ❑ Events that are raised by ASP.NET itself, both directly (such as the binding of data from a database) and indirectly (such as updating database records). These events give you an oppor- tunity to interact with the process of displaying or updating data, and allow you to fine tune the interface and provide user feedback. ❑ How some events can be cancelled, thus canceling any action they trigger, such as another event. In the example you saw that you can stop the deletion of data by using an event procedure. Now that you’ve had a look at events, and especially some related to data, it’s time to look at databases in more depth. The next chapter looks at some of the data controls and shows you how data can be fetched from the database and displayed for easy use by the user. 201 Events and Code 09_042583 ch06.qxd 4/4/06 2:44 PM Page 201 Exercises 1. In the Chapter06 project create a new Web Form called Lists.aspx and add a ListBox control to the page, and add three list items with values of One, Two, and Three. Add a Label control and a Button control to the page. In the Click event of the Button, display the selected value of the ListBox in the Label. 2. Modify Exercise 1 so that just selecting an item in the list posts back to the server (meaning you don’t need to click the button). You’ll need to add an event procedure to the ListBox, and in that event procedure you can use the same code from the Click event of the Button to display the selected value in the Label. Hint: The terms postback and automatic might be useful in your hunt for correct properties. 3. Modify the EditSquad.aspx example so that the GridView is refreshed when a new player is added to the squad. The technique is similar to the code you already have, but you’ll need to use a different event. Remember that you can use the drop-down lists in the code view to find the events. 202 Chapter 6 09_042583 ch06.qxd 4/4/06 2:44 PM Page 202 7 Reading Data The hallmark of dynamic web application pages is the capability to use information from a database. No other capability so widely expands the horizons of functionality for the visitor. The majority of information in an enterprise is held in databases, so it is imperative that a web applica- tion representing a business interact with that data. A tremendous effort by the ASP.NET 2.0 devel- opment team has reduced the knowledge and lines of code needed to work with data. This chapter and Chapter 8 explain how to implement the data-based features. This chapter covers several major ideas: ❑ The theory of using data in ASP.NET 2.0, including a brief overview of the theory and terminology of databases, an introduction to ASP.NET 2.0 data source controls and data- bound controls, and the role of VWD in creating data-based pages ❑ Data source controls ❑ Data-bound selection lists ❑ Various data-bound controls, including GridView, DataList, Repeater, DetailsView, and FormView ❑ Data source controls with parameters ❑ Implementing multiple data controls that work together ❑ Working with XML data By the end of the chapter, you will have the tools and experience to use ASP.NET 2.0 server-side controls to present on your pages information that comes from a database. Introducing Databases Before starting on the ASP.NET 2.0 data controls, take a moment to consider sources of data. Data can be broadly divided into one of three categories. Relational data is organized into sets of tables according to rules of normalization. This category includes the data held in Microsoft Access, 10_042583 ch07.qxd 4/4/06 2:45 PM Page 203 Microsoft SQL Server, Oracle, SAP, DB2, and MySQL. A second category of data resides in tree struc- tures, such as XML files, the Windows registry, and the Windows file system. Last, data can be held in a wide range of miscellaneous types, such as Excel files, text files, or proprietary formats. This book (as per the vast majority of web site data interaction) discusses relational data and XML files. Relational databases divide information into tables, and the tables contain records (also called rows). A record represents one instance of the topic of the table. A table contains multiple fields, or columns, that organize values by their type. For example, a table of employees could contain a record for each employee. The table’s columns may be NameFirst, NameLast, DateOfHire, and so forth. For each column there would be a value for each record. A group of tables makes a database in most management systems. In Microsoft SQL Server, which is used in this book, one or more databases together make an instance of the server. Typically, tables contain only the data. The description of how the data is organized, the names of fields, and restrictions all reside in a separate structure of the database called metadata. XML files are different from relational databases. First, instead of tables, the data is organized into a tree with branches of the tree holding finer and finer points of data. Each set of data and each individual datum are contained in a node. For example, an Employees XML file would have an Employees node that would represent the main trunk. Then there would be a limb for each employee. From that limb would be branches for FirstName, LastName, and so on. Second, an XML file is self-describing in that the metadata is included with the data. Each piece of information has an HTML tag that acts like a con- tainer that states the description of that data. For example, a datum like “John” would actually be stored as <NameFirst>John</NameFirst>. Although the self-descriptors can make an XML file huge, they make it easy to understand the data without having the metadata information. Almost all sources of data have a system that controls who is allowed to use the data. The first step in security is authentication, wherein the system determines who is asking to use it. The topic of authenti- cation was covered in detail in Chapter 4, so we won’t spend much time on it here. Basically, there are two types of authentication: Windows Authentication (also known as Trusted Security) and SQL Authentication. The decision of which authentication to use is made when the database is installed. With SQL Server Express, you have the option of Windows Authentication or Mixed. Mixed means you can use either Windows Authentication or SQL Authentication. SQL Server Express installs, by default, with Mixed Authentication. This book uses Windows Authentication. This book mainly uses Microsoft’s SQL Server. The product is sold with different sets of features, but for our use the simplest version (SQL Server Express) is adequate. Fortunately, Microsoft provides SQL Server Express free of charge, and automatically installs with the instructions given in this book for the setup. The beauty of SQL Server Express is that when you deploy your site to the public, all of your code fits without modification into the full-featured SQL Server. After you are authenticated (you prove that you actually are who you say you are), there will probably be a set of rights and limitations for your use of the data. First are restrictions in how you can look at data. Database administrators (DBAs) generally restrict direct access to tables. Instead, data may only be available to you through a view or query that contains limited fields or records. Second, you may have limits on how (or if) you can change data. Last, even if you have the right to change data, there may be restrictions (called constraints) on how data can be changed. To use Wrox United as an example, you generally cannot delete a team that is listed in the schedule (thus leaving the schedule with the logical fault of a game without an existing team). 204 Chapter 7 10_042583 ch07.qxd 4/4/06 2:45 PM Page 204 Using ASP.NET 2.0’s Data Controls Chapter 3 presented the idea that ASP.NET offers server-side controls. These controls contain code writ- ten by Microsoft that offers various behaviors, such as a drop-down list or a button. ASP.NET 2.0 has two sets of controls that are specific to working with data. The first set is data source controls that enable a page to connect to a source of data and to read from and write to that source. However, a data source control has no means to display data on an ASP.NET 2.0 page, which is where data-bound controls come into play. Data-bound controls display data to the user by rendering data onto a page. This chapter dis- cusses data source controls and the reading behaviors of data-bound controls. Almost all data source controls can work with almost all data-bound controls. This gives designers a mix-and-match solution. Pick the data source control that is optimized for the data and then pick a data- bound control that displays the information as desired. Introducing Data Source Controls ASP.NET 2.0 ships with several types of data source controls that are tailored to work with different types of data sources. These controls are as follows: ❑ The SqlDataSource control allows connections to most relational databases. The Sql in its name refers to databases that understand the SQL language. That includes almost every kind of database that holds its data in a relational format. Note that the Sql does not refer only to the Microsoft SQL Server database management system. SqlDataSource controls utilize one of several providers that are specific to different kinds of databases. The default provider is for Microsoft SQL Server. Another provider is for Oracle. Both of these are written in managed code, the most robust option in the .NET Framework. ASP.NET 2.0 contains an additional provider that can communicate with any database that is OLEDB-enabled (OLEDB is an acronym for Object Linking and Embedding for Databases). Because OLEDB is an old standard, it comprises almost every other database management system including IBM DB2, MySQL, and SAP. However, the provider for OLEDB connections is not written in managed code. That means it does not meet all the requirements of being .NET technology, but it still can work with .NET. We can expect third parties to publish more data source controls and providers and can hope that they are in proper managed code. ❑ The AccessDataSource control is a special case of the SqlDataSource control that contains a provider optimized for Microsoft Access. ❑ The XMLDataSource control allows connection to XML sources. If you begin writing more advanced scenarios, you will discover that OLEDB data source controls are not part of the System.Data hierarchy. These controls actually reside in the System.Web.UI.Controls namespace. But this point does not arise for most scenarios where you can just drag data controls from the toolbar. 205 Reading Data 10_042583 ch07.qxd 4/4/06 2:45 PM Page 205 ❑ The SiteMapDataSource control, a specialized form of the XMLDataSource control, is opti- mized for the specific architecture of the ASP.NET 2.0 web application site map (as you built in Chapter 2). ❑ The ObjectDataSource control connects to business objects you build yourself (discussed in Chapter 10). Regardless of which data source control (and in the case of the SqlDataSource, which provider) you use, the data source control will enable a set of behaviors for your ASP.NET 2.0 page. These include a connection to the database and enablement of behaviors such as reading and writing data, which are available to data-bound controls that display data and receive input from the user. In summary, the data source controls create the background infrastructure needed to use data. However, they do not create any rendering on the web page (see the next section for those capabilities). Rather, they make the data behaviors like reading and writing to data stores available to data-bound controls. Introducing Data-Bound Controls Data-bound controls provide the link between the data source controls and the user. They take the data and behaviors of the data source control and render it to the visitor. This division of labor works very well. You can select any data source control and link that to any of the data-bound controls. With just a few exceptions, it is a mix-and-match scenario. Data-bound controls encapsulate remarkable amounts of behavior. For example, the GridView control can not only display data in a table, but it offers sorting, selecting, paging through subsets, and one-click transition to data editing. If your needs extend beyond these capabilities, you can write custom code hooked into events exposed by the GridView control. There is one constraint on the compatibility of data source controls and data-bound controls. Each con- trol is optimized for tabular data, tree data, or custom class data. For example, XML data is organized as a tree and thus best accessed with the XMLDataSource control and displayed in Menu or SiteMapPath data-bound controls. SQL Server data is organized into tables and thus accessed with the SqlDataSource control and displayed in GridView (tables) or DetailsView. List-type data-bound controls can display either source of data. You can twist the controls to cross-utilize types of data, but in general it is best to stick to their intended purpose. Four general groups of data-bound controls ship with ASP.NET 2.0. Because there is overlap in their func- tionality, this chapter spends some time differentiating them. First you will look at their renderings, then a comparison chart, and finally a guide to selecting the correct data-bound control for your purposes. If you are familiar with older versions of ASP, the ASP.NET 2.0 data source controls instantiate ADO.NET objects. Therefore, ADO.NET provides the underlying tech- nology for data access. The creation and manipulation of ADO.NET objects for most scenarios is now handled automatically (and correctly and efficiently) by the higher- level data source control objects. 206 Chapter 7 10_042583 ch07.qxd 4/4/06 2:45 PM Page 206 The trick with data-bound controls arises in the selection. It can be confusing in the first attempts to get the correct control for your purpose. To help, the following sections organize the data-bound controls into four groups. Later in the chapter, you will practice using each of them in a series of exercises. Tabular Controls Tabular controls produce the classic HTML table listing the data of records, albeit with opportunity for significant enhancements. These controls show multiple records in rows and one or more fields from each record as columns. The GridView control shows one value (datum) in each cell in a table layout. The DataList and Repeater controls behave in the same way, and render each cell with all of the fields for one record. Figure 7-1 shows how these controls look in a browser. Figure 7-1 The GridView control offers the most behaviors, as it can read, edit, and select records. The DataList control allows reading and editing, whereas the Repeater is a read-only control. The name of DataList is a bit confusing because you have a separate set of List controls that are optimized for selecting a record. The DataList is a display control in a tabular format. Single Record Display Controls Single record controls (DetailsView and FormView) display one record at a time. You can think of them as a deck of playing cards in a pile face up. At any moment all of the cards are there, but you can only see the top one. You have to navigate down through the deck to see other cards (see Figure 7-2 for an example of the DetailsView control). Single record controls have navigation features to permit the visi- tor to go to the next record, jump to a specific record, or fly to the first or last record. The DetailsView control provides some default layout when you create the control, whereas the FormView control creates a blank slate upon which you create the entire layout. Both of these data-bound controls support the reading, editing, and creation of new records. Note that other controls, such as text boxes, can be data-bound. However, these inde- pendent controls are best connected to data in the context of a template within one of the controls just mentioned. This topic is discussed in detail in Beginning ASP.NET 2.0 Databases from Wrox, ISBN 0-4717-8134-7. 207 Reading Data 10_042583 ch07.qxd 4/4/06 2:45 PM Page 207 Selection List Controls Selection list controls are optimized to accept a user selection. These two controls display just one field from each record and stand by for a mouse-click. As shown in Figure 7-3, ListBox controls (right side of figure) are by default expanded, whereas DropDownList controls (left side of figure) display a single row until the user expands. As you would expect, these controls are display-only with no capability to change data. Figure 7-2 Figure 7-3 Tree Controls Tree controls are optimized to handle data that are stored in nodes rather than tables. The Menu control provides a slide-out dynamic so that when you pass your mouse over a menu choice the submenu slides out. The TreeView control gives the user the option to expand or collapse nodes (see Figure 7-4). The Menu control is on the left of Figure 7-4, and the TreeView control is on the right. The SiteMapPath con- trol offers a navigation trail that automatically updates based on the current page. 208 Chapter 7 10_042583 ch07.qxd 4/4/06 2:45 PM Page 208 [...]... source control will appear as follows in the Fixtures.aspx page: SelectCommand=”SELECT * FROM [Fixtures]” < /asp: sqldatasource> 7 216 Meanwhile, an addition has been created in section of the Web.config code In the actual Web.config file, the connection string runs on across... Data section of the Toolbox to the content area Open its smart task panel, as shown in Figure 7-22, and click Choose Data Source Click New Data Source for the wizard to create a data source control Figure 7-22 3 Select Database as the source and leave the name as SqlDataSource1 Click OK Use the WroxUnited connection string (not WroxUnited.mdf because that choice will create a new connection) 4 From... Source View and focus on the data source control Notice that it now lacks the actual values for the connection string Instead, you get a pointer to connectionString (which is understood to mean in the Web.config file) and within the connection strings to Wrox United Open the Web.config file Go to the section on connectionStrings The tag indicates another connection string within the section Following... command to an ASP. NET version 1.1 source of data DataSourceID is employed when you use ASP. NET 2.0 automatic binding to a data source control The GridView Control The GridView data-bound control provides the classic display of tabular data Each row represents one instance or record, and each column holds one field of data A cell within the table displays a value that is appropriate for its intersection... specify a provider for that source so that the named provider can override the default provider: 217 Chapter 7 . Wrox, ISBN 0- 47 17-81 34- 7. 20 7 Reading Data 10_ 0 42 5 83 ch07.qxd 4/ 4 /06 2: 45 PM Page 20 7 Selection List Controls Selection list controls are optimized to accept a user selection. These two controls. correctly and efficiently) by the higher- level data source control objects. 20 6 Chapter 7 10_ 0 42 5 83 ch07.qxd 4/ 4 /06 2: 45 PM Page 20 6 The trick with data-bound controls arises in the selection Data 10_ 0 42 5 83 ch07.qxd 4/ 4 /06 2: 45 PM Page 20 5 ❑ The SiteMapDataSource control, a specialized form of the XMLDataSource control, is opti- mized for the specific architecture of the ASP. NET 2. 0 web

Ngày đăng: 09/08/2014, 18:22

TỪ KHÓA LIÊN QUAN