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

BeginningASP.NET 2.0 with C# PHẦN 4 docx

76 345 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 76
Dung lượng 1,9 MB

Nội dung

(Inserting/Inserted) and for data being deleted (Deleting/Deleted). The present tense event ( Inserting, for example) is raised as the action is occurring, whereas the past tense event (such as Deleted) is raised after the event. For example, when deleting a row, the Deleting event is raised just before the row is deleted, and the Deleted event is raised after the event is raised. For some events, the fact that they are raised before the actual action takes place gives you the opportu- nity to cancel the event. For example, consider the EditSquad.aspx file, where the team owner can change the squad. One of the things the owner wants is to make sure that any players that left during the playing season remain in the database— so you can’t delete players between August 20 and May 31. To enable this, you need to allow deletion of players, but not within those dates. Give this a go in the next Try It Out. Try It Out Canceling Events 1. Open the EditSquad.aspx file in the Visual Web Developer designer, and add a Label control at the very end of the page. 2. Set the ID of the Label control to Message, and clear the Text property. 3. Select the DetailsDataSource control, and on the events list double-click into the box next to the Deleting event to have the event procedure created for you. 4. In the empty event procedure, add the following code: DateTime today = DateTime.Now; int startYear; int endYear; DateTime seasonStart; DateTime seasonEnd; if (today.Month > 5) { startYear = today.Year; endYear = today.Year + 1; } else { startYear = today.Year - 1; endYear = today.Year; } seasonStart = new DateTime(startYear, 8, 20); // 20th August seasonEnd = new DateTime(endYear, 5, 31); // 31st May if (today >= seasonStart && today <= seasonEnd) { e.Cancel = true; Message.Text = “Cannot delete players during the season”; } else { GridView1.DataBind(); Message.Text = “”; } 197 Events and Code 09_042583 ch06.qxd 4/4/06 2:44 PM Page 197 5. Save the file and from the right mouse menu select View in Browser. 6. Make sure your system date is set between August 20 and May 31. 7. Select a player and try to delete him. You’ll see a message telling you that players cannot be deleted during the season, and the player is not deleted. 8. Change the system clock so that the date is out of season — that is, between June 1 and August 19. 9. Select a player and try to delete him. You may want to add a new test player just so that you can delete him, to save you deleting real squad members. How It Works This example relies on the fact that the Deleting event is raised before the actual action takes place, which gives you the opportunity to cancel the event. One of the keys to how this works are the parame- ters of the event procedure, the declaration of which is shown here: protected void DetailsDataSource_Deleting(object sender, System.Web.UI.WebControls.SqlDataSourceCommandEventArgs e) You can see that the second parameter provides extra information, but not only that it allows you to send information back to ASP.NET. One of the properties of the parameter e is called Cancel, and if you set this to true, the event will be cancelled and the action (the deletion) will not take place. Take a look at the code used to determine whether or not the player should be deleted. You start with some declarations, which will be used to store date information: DateTime today = DateTime.Now; int startYear; int endYear; DateTime seasonStart; DateTime seasonEnd; The first line sets the variable today to the current date. The variables startYear and endYear indicate the year in which the season starts and ends, and seasonStart and seasonEnd are the actual dates for the start and end of the season. To determine the start and end year you see if the current date is after May. If it is, you know that the season has ended, or is already under way, so the start year is the current year and the end year is next year. If the current date is before May, you are in the second half of the season, so the start year was last year and the end year is the current year: if (today.Month > 5) { startYear = today.Year; endYear = today.Year + 1; } 198 Chapter 6 09_042583 ch06.qxd 4/4/06 2:44 PM Page 198 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 [...]... as text boxes, can be data-bound However, these independent 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 -47 17-81 34- 7 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... top-level nodes with the option to expand one subnode at a time Used to display a menu where there will be one selection TreeView Tree Read only Displays top-level nodes with option to expand one or many subnodes Used to display multiple subnodes simultaneously 210 Reading Data Data Source Controls and Data-Bound Controls Work Together As discussed in the previous two sections, ASP.NET 2.0 offers two... page The Properties window offers a graphical user interface for changing settings If you are working with code in Source View, you can move the insertion bar within a data control tag and press the space bar to get a list of the appropriate attributes in IntelliSense Last, VWD offers a very useful tool within wizards for building the SQL statements needed to display or modify data Instead of you typing... are presented in several chapters of our sister book, Beginning ASP.NET 2.0 Databases Data-Bound Controls Keep in mind the basic model of ASP.NET 2.0 for using data Two controls must be on the page: a data source control and the data-bound control The remainder of this chapter focuses on the various databound controls It starts with selection lists; moves on to the GridView, DataList, and Repeater;... user’s selection from a list box Items can be added to a list in three ways The first way adds items using individual ASP.NET 2.0 tags The second way binds the list to an array of values Finally, the items can be read from a data source Adding List Items with Individual ASP.NET 2.0 Tags When the items remain relatively static (for example, a list of states or provinces), you use hard coding to add items... (only those states with customers) Items can be added with simple tags as shown in the following code In this example, you create a drop-down list for users to pick a player position You want the user to see the full name of the position (such as Left Back), so that is the Text property After the user makes a selection you, as a programmer, will want to actually work with your code for... binding Binding, in ASP.NET 2.0, refers to the act of bringing data into a control For example, when you bind a ListBox to a data source control the information from the data source is actually brought into the ListBox control This is one of the few places in ASP.NET 2.0 where you use the version 1.x technique of performing binding as a distinct line of code In most cases in version 2.0, the data controls... Run the page Now the ListBox control only shows the months with games — 9 is left out Months will also automatically change if the Wrox United schedule adds games in another month How It Works Adding a ListBox control is easy with VWD’s drag-and-drop functionality In the hard-coded technique, you created an array of integers and filled it with what you expected would be useful values Then in the ListBox... control and is not directly part of the data binding 2 24 Reading Data Last, back up in the code, you added a line to the Page_Load event that instructs ASP.NET 2.0 to actually bind the data of the array to the data-bound control Two problems exist with this technique First, it uses the ASP.NET version 1.1... also get rid of the binding line (which ASP.NET 2.0 will do for you when you use an ASP.NET 2.0 data source control) Notice the subtle but important difference between two properties of the ListBox control DataSource is used when you are binding by explicit 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 . schedule with the logical fault of a game without an existing team). 20 4 Chapter 7 10_ 0 42 5 83 ch07.qxd 4/ 4 /06 2: 45 PM Page 20 4 Using ASP .NET 2. 0 s Data Controls Chapter 3 presented the idea that ASP .NET. 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- 47 17-81 34- 7. 20 7 Reading Data 10_ 0 42 5 83 ch07.qxd 4/ 4 /06 2: 45 . deletion Allowed? Event Cancelled Event raised Deleted Yes No Event Runs 20 0 Chapter 6 09 _0 42 5 83 ch06.qxd 4/ 4 /06 2: 44 PM Page 20 0 ❑ Application_End, which is raised when the application stops. ❑ Session_Start,

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

TỪ KHÓA LIÊN QUAN