Professional VB 2005 - 2006 phần 7

Chia sẻ: Hà Nguyễn Thúy Quỳnh | Ngày: | Loại File: PDF | Số trang:110

lượt xem

Professional VB 2005 - 2006 phần 7

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Bây giờ chạy các ứng dụng. Các bố trí ban đầu sẽ được tương tự như các thiết kế bố trí thời gian. Tuy nhiên, nếu bạn thay đổi kích thước các hình thức khoảng một nửa chiều rộng ban đầu của nó, cách bố trí của các hộp văn bản sẽ thay đổi.

Chủ đề:

Nội dung Text: Professional VB 2005 - 2006 phần 7

  1. Chapter 17 Cross-Page Posting The way in which Active Server Pages 2.0/3.0 (also called classic ASP) worked was that values from impo PDF Merge and posted Unregistered Version were usually steps in a process that the end user forms were usually Split to other pages. These pages - worked through. With the introduction of ASP.NET on the other hand, pages in this environment posted back results to themselves in a step called a postback. One of the biggest requests of Web developers in the ASP.NET world has been the ability to do postbacks not only to the page from whence the values originated, but also the ability to do postbacks to other pages within the application. This new feature is something that has been provided with the release of ASP.NET 2.0. Cross-page posting (as it is referred) is an easy functionality to achieve now. It gives you the ability to post page values from one page (Page1.aspx) to an entirely different page (Page2.aspx). Normally, when posting to the same page (as with ASP.NET 1.0/1.1), you could capture the postback in a postback event as shown here: If Page.IsPostBack Then ‘ do work here End If Now, let’s take a look at Page1.aspx and see how you accomplish cross-page posting with ASP.NET 2.0. Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Label1.Text = “Your name is: “ & TextBox1.Text & “” & _ “Your appointment is on: “ & Calendar1.SelectedDate.ToLongDateString() End Sub Cross-Page Posting What is your name? When is your appointment? 628
  2. ASP.NET 2.0 Advanced Features impo PDF Merge and Split Unregistered Version - With Page1.aspx, you can see that there is nothing really different about this page — except for the Button2 server control. This page contains a new attribute which you will find with the Button, ImageButton, and LinkButton controls — the PostBackUrl attribute. The value of this attribute points to the location of the file that this page should post to. In this case, the PostBackUrl attribute states that this page should post to Page2.aspx. You can see that this is the only thing needed on the Page1.aspx to cause it to post back to another page. As for Button1, you can see that this is a simple button which will cause the page to post back to itself. This is nothing new as this has been the case even in ASP.NET 1.x. You can see the event handler for this postback in the OnClick attribute within the Button1 control. Pressing this button will cause the page to post back to itself and to populate the Label1 control that is at the bottom of the page. Clicking on the second button, though, will post to the second page, which is shown here: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim pp_TextBox1 As TextBox Dim pp_Calendar1 As Calendar pp_TextBox1 = CType(PreviousPage.FindControl(“TextBox1”), TextBox) pp_Calendar1 = CType(PreviousPage.FindControl(“Calendar1”), Calendar) Label1.Text = “Your name is: “ & pp_TextBox1.Text & “” & _ “Your appointment is on: “ & _ pp_Calendar1.SelectedDate.ToLongDateString() End Sub Second Page In this page, the first step is that in the Page_Load event, instances of both the TextBox and Calendar controls are created. From here, these instances are populated with the values of these controls on the previous page (Page1.aspx) by using the PreviousPage.FindControl() method. The String value 629
  3. Chapter 17 assigned to the FindControl method is the Id value of the ASP.NET server control from the originating page (in our case, TextBox1 and Calendar1). Once you have assigned the values to these control instances, you can then start working with the new controls and their values as if they were posted from the same page. impo PDF Merge and Split Unregistered Version - You can also expose the server controls and other items as properties from Page1.aspx. This is illustrated here in this partial code sample: Public ReadOnly Property pp_TextBox1() As TextBox Get Return TextBox1 End Get End Property Public ReadOnly Property pp_Calendar1() As Calendar Get Return Calendar1 End Get End Property Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Label1.Text = “Your name is: “ & TextBox1.Text & “” & _ “Your appointment is on: “ & Calendar1.SelectedDate.ToLongDateString() End Sub Once you have exposed the properties you want from Page1.aspx, then you can easily get at these properties in the cross-page postback by then using the new PreviousPageType page directive. This is illustrated here in the following example: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Label1.Text = “Your name is: “ & PreviousPage.pp_TextBox1.Text & “” & _ “Your appointment is on: “ & _ PreviousPage.pp_Calendar1.SelectedDate.ToLongDateString() End Sub After your properties on Page1.aspx, you can access them easily by strongly typing the PreviousPage property on Page2.aspx by the use of the PreviousPageType directive. The PreviousPageType directive specifies the page the post will come from. Using this directive allows you to specifically point at Page1.aspx. This is done using the VirtualPath attribute of the PreviousPageType directive. The VirtualPath attribute takes a String value whose value is the location of the directing page. 630
  4. ASP.NET 2.0 Advanced Features Once this association has been made, you can then use the PreviousPage property and you will see that the pp_TextBox1 and pp_Calendar1 properties that were created on Page1.aspx are now present in Visual Studio 2005’s IntelliSense. You will find that working with the PreviousPage property is a bit Merge and Split Unregistered Version - 17-1. easier and is less error prone than using weak-typing. This is shown here in Figure impo PDF Figure 17-1 One thing to be careful of is to guard against browsers hitting a page that is expecting information from a cross-page post and this action causing errors if the information the second page is expecting isn’t there. Pages that were looking for postback information was something you always had to guard against before — even when dealing with ASP.NET pages (1.0/1.1) that performed postbacks to them- selves. With standard pages that aren’t cross-page posting, you would protect your code from this post- back behavior through the use of the Page.IsPostBack property as shown here: If Page.IsPostBack Then ‘ code here End If 631
  5. Chapter 17 When cross-page posting, you will want to use the Page.IsCrossPagePostBack property. impo PDF Merge and Split Unregistered Version - Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) If Page.IsCrossPagePostBack Then Label1.Text = “Your name is: “ & PreviousPage.pp_TextBox1.Text & “” & _ “Your appointment is on: “ & _ PreviousPage.pp_Calendar1.SelectedDate.ToLongDateString() Else Server.Transfer(“Page1.aspx”) End If End Sub In this example, if someone hits this page without going to Page1.aspx first to get cross-posted to Page2.aspx, then the request will be checked to see if the request is a cross-post. If it is (checked using the Page.IsCrossPagePostBack property), then the code is run, otherwise the request is redirected to Page1.aspx. ASP.NET Advanced Compilation The last chapter, Chapter 16, covered how the compilation process works in ASP.NET. You can notice this compilation process and how it works when you hit one of the ASP.NET pages you have built for the first time in the fact that it takes a few seconds for the page to be generated. This is due to the fact that the ASP.NET application is being compiled into intermediate code when you first hit that page. One thing that makes this situation even less enjoyable is that each and every page will have this lag when that particular page is first requested. In a page’s first request, ASP.NET compiles the page class into a DLL and then this is written to the disk of the Web server. The great thing about ASP.NET is that on the second request, instead of need to com- pile the page again, the DLL is accessed instead — making the request for the page far quicker than oth- erwise. You will notice this yourself if you hit the refresh button on your browser to re-request the same page. You will notice a new snappiness to the page. Due to how the pages are compiled in ASP.NET, whenever you make changes to your pages within your application, the application is recompiled again and each and every page will again have this initial drag as it is compiled. This can be quite a pain if you are working with larger sites and you really can’t afford this kind of pause to page generation (even if it is only one time). ASP.NET 2.0 includes a couple of precompilation tools so that you don’t have to experience this cost of page-by-page compilation. Both of these processes precompile your entire application at once. The first precompilation option is to invoke precompile.axd directly in the browser as if it was a page of your application. If you are using the Web server that is built into Visual Studio 2005, your request would be structured in the following format: http://[host]:[port]/[application name]/precompile.axd 632
  6. ASP.NET 2.0 Advanced Features Though if you are using Microsoft’s Internet Information Server, your request would be structured in the following format: http://[host]/[application name]/precompile.axd impo PDF Merge and Split Unregistered Version - Once run, and if successful, you will be notified in large bold text: The application was successfully precompiled. If there is an error on any of the pages of your application, you will be notified of this through this com- pilation process which will make note of the page and line of the error. If successful, this precompilation process will have gone through each element of your application and will have successfully compiled it all into a DLL, thereby removing the churn you would normally experience hitting each of your pages for the first time. The other method of precompilation is for when you are going to need to precompile your applications that are meant to be deployed. Contained within the .NET Framework 2.0, you will find a tool — aspnet_compiler. You will find this tool at C:\Windows\Microsoft.NET\Framework\v2.0.[xxxxx]\. This is a command-line tool and you will simply need to navigate the aforementioned location to use it. In the simplest case, you would use the following structure to precompile your ASP.NET application. aspnet_compiler –v [Application Name] –p[Physical Location] [Target] For an example of using this compiler, let’s suppose that you are compiling an application called Wrox which is located at C:\Websites\Wrox. For this, you would use the following construction: aspnet_compiler –v /Wrox –p C:\Websites\Wrox c:\Wrox If successful, the application will be compiled. The output of a successful compilation is shown here in Figure 17-2. Figure 17-2 The nice thing about this compilation process is that it hides your code for you by packaging it into a DLL where it will be quite hidden for casually prying eyes. If you look at the target location of the com- pilation process, you will still see the same structure and files as you had before, but if you look at the contents of the .aspx files, you will see the following: This is a marker file generated by the precompilation tool, And should not be deleted! 633
  7. Chapter 17 If you look at what was compiled by the aspnet_compiler tool, you will find a Code.dll in the bin folder. This is where all the code from the pages is located. To deploy this precompiled application, you will not only need to move the Code.dll file, but each folder and placer file which was generated by the PDF Merge and Split Unregistered Version - http://www.simpopdf.comASP.NET compiler. Move everything that was generated by the compiler to the target server and the impo application will be able to run without any concerns. One important point about this second precompilation process is that it doesn’t precompile each and every file that is contained within your application. The files that are excluded from the precompilation process include: ❑ HTML files ❑ XML files ❑ XSD files ❑ Web.config files ❑ Text files If you want these types of files also precompiled along with the rest of your files, one trick is to change the file extensions of the files that allow for it to be an .aspx extension. Doing this will cause these files’ contents to also be batched in with the content from the other pages in the compilation process, thereby obfuscating their contents. Master Pages Many Web applications are built so that each of the pages of the application has some similarities. For instance, there might be a common header that is used on each and every page of your applications There also may be other common page elements including navigation sections, advertisements, footers, and more. It really isn’t so common to have your Web pages each have their own unique look and feel to them. What people are looking for in their applications is some kind of commonality to give the end user what works through a multipaged application. What is really needed for these types of applications is a way to provide a template that can be used by your pages — a sort of visual inheritance (as can be done with Windows Forms). With a new feature in ASP.NET 2.0 called master pages, you can now employ visual inheritance in your Web applications. The use of master pages means that you are working with a template file (the master page) which has a .master extension. Once a .master page is created, you can then take a content page, with an .aspx exten- sion, and make an association between the two files. Doing this will allow ASP.NET to take these two files and combine them into a single Web page to display in a browser. Figure 17-3 shows a diagram of how this works. 634
  8. ASP.NET 2.0 Advanced Features Master Page Content Page MyMaster.master Default.aspx impo PDF Merge and Split Unregistered Version - M C MC Combined Page Default.aspx Figure 17-3 Let’s now take a look at how we would make this work by first creating the master page. Creating a Master Page The first step is to create a template that will end up being our master page. You can build a master page using any text editor (such as Notepad), but you will find it far easier to use Visual Studio 2005 or Visual Web Developer, as I will show you here. Start within the Solution Explorer. Right-click on the solution and select Add New Item. In the Add New Item dialog, you will find the option to add a master page to the solution. This is illustrated here in Figure 17-4. Your master page options are quite similar to that of working with a standard .aspx page. You can either create master pages to be inline or you can have master pages which utilize the code-behind model. If you wish to use the code-behind model, make sure that you have the ‘Place code in separate file’ check box checked in the dialog — otherwise leave it blank. Creating an inline master page will produce a single .master file. Using the code-behind model produces a .master file in addition to a .master.vb or .master.cs file. 635
  9. Chapter 17 impo PDF Merge and Split Unregistered Version - Figure 17-4 A master page should be built so that it contains one or more content regions that are utilized by the con- tent pages. The following master page example (named Wrox.master) contains two of these content areas: Wrox The Wrox Company Homepage 636
  10. ASP.NET 2.0 Advanced Features impo PDF Merge and Split Unregistered Version - Copyright 2006 - Wrox The first thing to notice is the directive at the top of the page instead of the standard directive. This specifies that this is a master page and cannot be generated without a content page associated with it. It isn’t a page that you can pull up in the browser. In this case, the Master direc- tive simply uses the Language attribute and nothing more, but you will find that it has a number of other attributes at its disposal to fine-tune the behavior of the page. The idea is to code the master page as you would any other .aspx page. This master page contains a simple table and two areas that are meant for the content pages. These areas are defined with the use of the ContentPlaceHolder server control. This page contains two ContentPlaceHolder controls. It will be only in these two specified areas where content pages will be allowed to interject content into the dynamically created page (as you will shortly see). The nice thing about working with master pages is that you don’t only have to work with them in the code view of the IDE, but Visual Studio 2005 also allows for you to work with them in the design view as well. This is illustrated here in Figure 17-5. You can see that in this view, you can work with the master page by simply dragging and dropping con- trols onto the design surface just as you would with any typical .aspx page. Creating the Content Page Now that there is a master page in your project that you can utilize, the next step is to create a content page which will do just that. To do this, again right-click on the solution from within the Solution Explorer of Visual Studio 2005 and select Add New Item. This time though, we are going to add a typical Web Form to the project. Though, before you hit the Add button, be sure that you check the Select a Master Page check box in the dialog. This informs VS2005 that we are going to be building a content page that will be associated with a master page. Doing this will then pull up a new dialog, which will allow you to select a master page to associate this new file with. This is shown here in Figure 17-6. 637
  11. Chapter 17 impo PDF Merge and Split Unregistered Version - Figure 17-5 Figure 17-6 638
  12. ASP.NET 2.0 Advanced Features In this case, if you have been following along with the example, you should only have a single master page available in the dialog, though it is possible to have as many different master pages as you wish in a single project. Select the Wrox.master page and press the OK button. impo PDF Merge and Split Unregistered Version - The page created will have only a single line of code to it: There is quite a bit that is different with this file than a typical .aspx page. First off, there is none of the default HTML code, script tags, and DOCTYPE declarations that are the norm. The other change is the addition of the MasterPageFile attribute in the Page directive. This new attribute makes the associa- tion to the master page which will be used for this content page. In this case, it is the Wrox.master file that we created earlier. Though there isn’t much to show while in the Source view of Visual Studio when looking at a content page, the real power of master pages can be seen when you switch to the Design view of the same page. This is shown here in Figure 17-7. Figure 17-7 639
  13. Chapter 17 This view shows you the entire template and the two content areas that this content page is allowed to deal with. All the grayed-out areas are off limits and do not allow for any changes from the content page — while the lighted areas allow for you to deal with any type of content you wish. For instance, not PDF Merge place raw text in these content areas, but anything that you would normally place into a only can you and Split Unregistered Version - impo typical .aspx page can also be placed in these content areas as well. For an example of this, let’s create a simple form in one of the content areas and place an image in the other. This code is shown here: Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Label1.Text = “Hello “ & Textbox1.Text End Sub Enter in your name: Even looking at this example here, you can see the differences between a content page and a regular .aspx page. Most importantly, this page doesn’t contain any element or any of the struc- ture that you would normally see in a typical Web form. All of this content instead is stored inside the master page itself. This content page contains two Content server controls. Each of these Content server controls map to a specific control from the master page. This association is made through the use of the ContentPlaceHolderID attribute of the Content control. ... Just like typical .aspx pages, you can create any event handlers you might need for your content page. This particular example uses a button-click event for when the end user submits the form. Running this example would produce the following results as shown in Figure 17-8. 640
  14. ASP.NET 2.0 Advanced Features impo PDF Merge and Split Unregistered Version - Figure 17-8 Declaring the Master Page Application-Wide As shown in our examples thus far, we have been declaring the master page from the content page through the use of the MasterPageFile attribute of the Page directive. You can apply this attribute to each and every one of your content pages or you can make this declara- tion in the web.config file of your application as shown here: From the node in the web.config file, you make the declaration that all your content pages will use a specific master page through the use of the masterPageFile attribute. Doing this means that your content pages can simply use the following Page directive construction: The nice thing with making the master page declaration in the web.config file is you don’t have to make this declaration on any of your solution’s content pages, and if you decide to change the template and associate all the content pages to a brand new master page, it is a simple change in one spot to change each and every content page instantaneously. Doing this will have no effect on the regular .aspx pages in your solution. They will still function as normal. Also, if you have a content page that you wish to associate to a different master page than the one that is specified in the web.config file, then you simply need to use the MasterPageFile attribute in the Page directive of the page. This will override any declaration that you might have in the web.config file. 641
  15. Chapter 17 Providing Default Content in Your Master Page Earlier, we showed how to use a basic ContentPlaceHolder control. In addition to using it as it was shown, you also create ContentPlaceHolder controls that contain default content. This is illustrated here: impo PDF Merge and Split Unregistered Version - Here is some default content! For default content, you can again use whatever you want, including any other ASP.NET server controls. A content page that uses a master page that contains one of these ContentPlaceHolder controls can then either override the default content — by just specifying content (which overrides the original con- tent declared in the master page) — or just keep the default content contained in the control. Data-Driven Applications ASP.NET 2.0 provides some unique data access server controls that make it easy for you to get at the data you need. As data for your applications finds itself in more and more types of data stores, it can sometimes be a nightmare to figure out how to get at and aggregate these information sets onto a Web page in a simple and logical manner. ASP.NET data source controls are meant to work with a specific type of data store by connecting to the data store and performing operations such as Inserts, Updates, and Deletes — all on your behalf. The following table details the new data source controls at your disposal. Data Source Control Description Enables you to work with any SQL-based database, such as Microsoft SqlDataSource SQL Server or even Oracle Enables you to work with a Microsoft Access file (.mbd) AccessDataSource Enables you to work with a business object or a Visual Studio 2005 ObjectDataSource data component Enables you to work with the information from an XML file or even a XmlDataSource dynamic XML source (for example, an RSS feed) Enables you to work with the hierarchical data represented in the site SiteMapDataSource map file (.sitemap) ASP.NET itself provides a number of server controls that you can use for data-binding purposes. That means that you can use these data source controls as the underlying data systems for a series of controls with very little work on your part. These data-bound controls in ASP.NET include: 642
  16. ASP.NET 2.0 Advanced Features ❑ ❑ ❑ ❑ impo PDF Merge and Version - Split Unregistered ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ The newest and most thought of control in the bunch is the GridView control. This control was intro- duced in ASP.NET 2.0 and makes the DataGrid control more or less obsolete. The GridView control allows paging, sorting, and editing with very little work on your part. This next section takes a look at using the GridView control with SQL Server and allowing for these advanced features. Using the GridView and SqlDataSource Controls For an example of using these two controls together to display some information, let’s turn to Visual Studio 2005. Start a new page and drag and drop a GridView control onto the design surface of the page. Pulling up the smart tag for the control on the design surface, you can click the Auto Format link to give your GridView control a better look and feel rather than the default look of the control. Next, drag and drop an SqlDataSource control onto the design surface. This control is a middle-tier component, and therefore, it will appear as a gray box on the design surface. The first step is to config- ure the SqlDataSource control to work with the data we want from our Microsoft SQL Server instance. This is shown in Figure 17-9. Figure 17-9 Working through the configuration process for the SqlDataSource control, you must choose your data connection and then whether you want to store this connection in the web.config file (shown in Figure 17-10). This is highly advisable. 643
  17. Chapter 17 impo PDF Merge and Split Unregistered Version - Figure 17-10 From this configuration process, you also get to choose the table that you are going to work with, and test out the queries that the wizard will generate. For our example, select the Customers table and select every row by checking the * check box. This is illustrated in Figure 17-11. Once you work through the configuration process, you will then notice that your web.config file has changed to now include the connection string. ... 644
  18. ASP.NET 2.0 Advanced Features impo PDF Merge and Split Unregistered Version - Figure 17-11 Once you have configured the SqlDataSource control, the next step is to tie the GridView control to this SqlDataSource control instance. This can be done through the GridView control’s smart tag as shown here in Figure 17-12. You can also enable paging and sorting for the control in the same form. Figure 17-12 645
  19. Chapter 17 The code generated by the wizard (it would also be how you would code it yourself) is shown here: impo PDF Merge and Split Unregistered Version - GridView Example 646
  20. ASP.NET 2.0 Advanced Features Let’s first examine this code by looking at the SqlDataSource control. This control has some important attributes to pay attention to. The first is the SelectCommand attribute. This is the SQL query that you will be using. In our case, it is a Select * From [Customers] query (meaning that we are grabbing everything from the Customers table of the Northwind database). The second attribute to pay attention to is the ConnectionString attribute. The interesting thing with this attribute is the use of to get at the connection string. This value points at the settings that are placed inside the web.config file for those that don’t want to hard-code their connection strings directly in the code of their pages. If you did want to do this, you would use something similar to the following construction: ConnectionString=”Server=(local);Trusted_Connection=True;Integrated Security=SSPI; Persist Security Info=True;Database=Northwind” Now looking to the GridView control, you can see how simple it was to add the ability to perform pag- ing and sorting capabilities to the control. It was simply a matter of adding the attributes AllowPaging and AllowSorting to the control and setting their values to True (they are set to False by default). Each of the columns from the Customers table of the Northwind database are defined in the control through the use of the control, a subcontrol of the GridView control. The BoundField control allows you to specify the header text of the column through the use of the HeaderText attribute. The DataField attribute actually ties the values that are displayed in this column to a particular value coming from the Customers table, and the SortExpression attribute should use the same values for sorting — unless you are sorting on a different value than what is being displayed. In the end, your page should look something similar to the following as shown here in Figure 17-13. 647



Đồng bộ tài khoản