The book of visual basic 2005 net insight for classic vb developers 2006 - phần 9 pdf

51 249 0
The book of visual basic 2005 net insight for classic vb developers 2006 - phần 9 pdf

Đ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

Web Forms and ASP.NET 391 Figure 12-1: Creating an ASP.NET website Empty Web Site creates a new web application with no files at all. Of course, you can easily add new web pages and web services as you see fit. Personal Web Site Starter Kit creates a full-fledged personal website, complete with a standardized look and feel, an integrated navigation system, and some basic web pages (like Resume.aspx, Download.aspx, and Links.aspx). You can use this project to learn more about ASP.NET after you’ve finished this chapter. ASP.NET Crystal Reports Web Site creates a new web application with a Default.aspx page that’s designed to show a database-driven report using the Crystal Reports. This is a rarely used specialty feature. The Location box is more important. It allows you to tell Visual Studio where you’ll store your website files. Typically, you’ll choose File System (as in Figure 12-1), and then use a directory somewhere on your computer. That’s sufficient for creating and testing an application. When you’re ready to make your work available to a crowd of eager web surfers, you’ll then upload your files to a web server. Unlike other types of Visual Basic projects, you can’t create a new website project without saving it. NOTE The other location options allow you to create your application directly on a web server. You can use HTTP if you want to directly connect to an IIS web server and create your website. (This might be the case if you’re working with a test web server on your computer or local network.) You can also use FTP if you want to upload your files to a remote web server. Neither option is commonly used at the development stage. As mentioned earlier, it’s always better to create a test version of your website, perfect it, and only then upload it to a live web server that other people can access. Once you’ve chosen your location, click OK to create your website. You’ll start out with a relatively small set of files, as shown in Figure 12-2. bvb_02.book Page 391 Thursday, March 30, 2006 12:39 PM 392 Chapter 12 Figure 12-2: Initial files for a web application Ingredients of an ASP.NET Project Every web project is made up of the following files: web.config This file allows you to fine-tune advanced settings that apply to your entire application, including security and state settings. These options are outside the scope of this chapter, but you can read up on them in the Visual Studio Help. .aspx files These files are the ASP.NET web pages. Each web form you create will have an .aspx file that contains controls and formatting information. The .aspx file is sometimes called the presentation template of a web form. When you start a new website, Visual Studio adds one file—a Default.aspx page that represents your home page (the default starting page for your web application). .vb files These files are used to hold the code “behind” each web form. For exam- ple, a typical web form named HelloWorld would have its visual layout stored in the file HelloWorld.aspx, and its event-handling code in the Visual Basic file HelloWorld.aspx.vb. The Web Form Designer links these files together automatically. NOTE You might think that it is a serious security risk to have your source files located in a pub- licly accessible place, like a folder on a web server. However, ASP.NET is configured to automatically reject browser requests for configuration files like web.config and requests for any .vb file. ASP.NET also includes deployment tools that let you precompile your source code so that it won’t be readable to anyone, even the administrators managing the website. You can add a new web page to your application by selecting Website Add New Item. The most common type of item you’ll add is a web form. It’s recommended that you always keep the Place Code In Separate File check box selected, as in Figure 12-3. This tells ASP.NET to create an .aspx file for the page design (which contains HTML markup and ASP.NET control tags) and a separate .vb file with your event handler code. This separation makes it easier to program your page without worrying about the HTML details, and it’s the approach used in this chapter. bvb_02.book Page 392 Thursday, March 30, 2006 12:39 PM Web Forms and ASP.NET 393 Figure 12-3: Adding a web form TIP The Select Master Page option allows you to create web forms that are based on other web form templates, similar to the way that visual inheritance works with forms. Master pages aren’t covered in this chapter, although you can learn more in the Visual Studio Help (look for the index entry “master pages”). You can also add other types of resources to a web project, like ordinary HTML pages, style sheets (.css files), images to which you plan to link, and so on. When you create a web application, Visual Studio doesn’t place project (.vbproj) and solution (.sln) files in your website directory (as it does with other project types). Instead, it stores these files in a user-specific location in the Visual Studio projects directory (which is typically some- thing like c:\My Documents\Visual Studio 2005\Projects). This keeps your website directory clean and uncluttered, containing only the files you actually need. It also simplifies deployment. Best of all, the project and solution files aren’t required for deployed web applications, so if you accidentally delete them (or you don’t copy them when you transfer a website to another development computer), Visual Studio will quietly re-create new ones. NOTE The only important data that’s stored in the project and solution files are your debug settings (for example, any breakpoints you create) and a list of other projects that you want to load in the same solution for testing purposes (such as additional components that your website uses). bvb_02.book Page 393 Thursday, March 30, 2006 12:39 PM 394 Chapter 12 Designing Web Forms Web forms are designed to work as much like Windows forms as possible. However, there are still some basic differences between the two. There is no direct way to display a Windows-style dialog box from a web page, so throw away any ideas about using floating tool windows, message boxes, and multiple- document interfaces. A web form’s ultimate destination is an HTML page, to be delivered to a user working on an Internet browser. The ASP.NET engine may make use of JavaScript or Dynamic HTML to improve the appearance of your page if it detects that the client’s browser supports these enhancements, but every web form ultimately boils down to basic HTML. That said, you’ll find that web forms aren’t programmed like static web pages. Unlike ASP pages, which were often created with cryptic Response.Write() commands, a web form can (and usually should) be composed entirely of web controls that have properties and events, just like the controls in a Windows form. ASP.NET provides this kind of magic by using server-side controls. The basic idea behind a server-side control is that the display of the control is sent to the user in HTML, but the user’s interaction with the control is handled at the server. All of the web controls in ASP.NET are server-side controls. The Basic Controls To add a web control, you drag the control you want from the Toolbox (on the left) and drop it onto your web page. The controls in the Toolbox are grouped in a number of categories based on their function. Here’s a quick overview of the different groups: Standard This group has all the essentials, including web controls like labels, buttons, and text boxes, all of which closely resemble their Windows counterparts. You’ll use this group most often. Data This group contains controls for ASP.NET data binding, including con- trols for rich grid data display. Validation This group contains validators—controls that automatically display error messages when the input in another control (usually a text box) is invalid. Navigation This group contains controls that can help surfers navigate through all the pages of a website, including the snazzy TreeView control. Login This group contains security-related controls that allow you to add pages for logging in, creating users, and retrieving passwords. WebParts This group contains specialized controls that work with WebParts, ASP.NET’s model for portal sites. bvb_02.book Page 394 Thursday, March 30, 2006 12:39 PM Web Forms and ASP.NET 395 HTML This group contains plain HTML tags that don’t have any server-side interactivity. NOTE You can convert any piece of static HTML into a server control by right-clicking it and choosing Run As Server Control. This transforms the HTML tag into an HTML server control, which is a more limited type of server-side control than the other control types in the Toolbox. HTML server controls are primarily useful for backward compati- bility when migrating an HTML page or a classic ASP page to ASP.NET. The arsenal of ASP.NET controls is truly impressive—in fact, there are many more controls for ASP.NET than for Windows Forms applications. Adding Controls to a Web Form The Web Form Designer provides many of the same controls as the Windows Form Designer, including labels, text boxes, and buttons. Unlike the Win- dows Form Designer, the Web Form Designer uses flow layout, which means elements are positioned relative to each other, rather than in absolute coordinates. In a Windows application, every control is lined up according to an invis- ible grid. In a web application, controls are positioned one after another, like in a word processor. That means if you add more content to one element and it gets larger, the following elements are bumped down the page to make room, which is a clear advantage when dealing with large, variable amounts of content (as often found in web pages). NOTE Flow layout can be just as useful in a Windows application, although it’s not as often used for this purpose. In Chapter 4, you took a quick look at layout controls like the FlowLayoutPanel that use this system of arranging controls. The future holds even more—the next-generation framework for Windows user interface (named Windows Presentation Foundation, or WPF) makes flow layout the new standard. WPF is cur- rently an early alpha technology that will feature in Windows Vista, the next version of the Windows operating system. Flow layout also has a disadvantage: namely, you can’t place controls exactly. Instead, you need to add spaces and hard returns to position them on the page. You also need to drag and drop controls onto the page instead of drawing them on the page. This approach can take a little getting used to. TIP Technically, it is possible to position elements using absolute coordinates in a web page, but in order to do it you need to use the advanced formatting muscle of cascading style sheets (CSS). Usually flow layout is easier and more flexible, but if you want to learn more about grid layout with CSS, see www.w3schools.com/css/css_positioning.asp. Style sheets are also a great way for formatting entire web pages (without having to set font and color settings for each individual control). Getting pages to look right in flow layout mode takes a little bit of practice. To see the potential problem, take a look at the MetricConverter page shown in Figure 12-4. It has all the necessary controls, but getting them to line up properly using nothing but spaces and hard returns is iffy at best. bvb_02.book Page 395 Thursday, March 30, 2006 12:39 PM 396 Chapter 12 Figure 12-4: A first crack at designing a page Fortunately, a few simple tricks can save a lot of trouble: Use invisible tables to line up columns (for example, a series of text labels with text boxes). To add a table to your page, use the Table control from the HTML group. You can then add or remove columns and rows, resize it, and so on. NOTE Don’t use the table from the Standard group. This is a dynamic table that you can interact with in code. However, it’s not as convenient for layout because you can’t edit it using the Web Form Designer. Use panels to get a nice border around a group of controls, separating them from the rest of page. The easiest way to do this is to use the Div control (which stands for division) from the HTML group or the Panel control in the Standard group. You can format web controls using properties like Font, ForeColor, BackColor, and so on. However, this is tedious. In Windows applications, you had a shortcut—you could adjust these properties in the main form, and they’d automatically apply to all contained controls, unless the con- trols explicitly overrode them. A similar trick is possible in web pages using the Div and Panel controls. Any formatting you apply to the Div or Panel controls affects everything inside. However, the Properties window isn’t the way to format the Div control—instead, right-click it, and choose Style to set border, color, margin (external spacing), padding (internal spacing), and font options. NOTE If you’re a web guru, it may interest you to know that ASP.NET performs almost all its formatting using CSS. However, you don’t need to learn the details—instead, you simply configure the controls, and the appropriate style tags are set automatically. Figure 12-5 shows the revamped MetricConverter page. Now it has a Div that applies a background color, the well supported Verdana font, and a border. Inside the Div is a table that keeps the labels and text boxes properly aligned. bvb_02.book Page 396 Thursday, March 30, 2006 12:39 PM Web Forms and ASP.NET 397 Figure 12-5: Designing a better page Before continuing, try creating this page yourself so that you can follow through the rest of the example. Running a Web Page You can try out your simple MetricConverter web page, and see what it looks like in a browser, by running it. Just click the Start button in Visual Studio as you would with a Windows application. When you run a web application, Visual Studio starts up its integrated web server to handle the requests and launches your default web browser to show you the web page output. The first time you run a web application, Visual Studio will inform you that it needs to edit the web.config file to add a setting that allows debugging (see Figure 12-6). Choose OK to make the change and continue. Figure 12-6: Allowing debugging When you’re ready to deploy your final application, you’ll want to remove this setting for the sake of optimum performance. To do so, find this line in the web.config file: <compilation debug="true" strict="false" explicit="true"> and remove the debug="true" attribute. bvb_02.book Page 397 Thursday, March 30, 2006 12:39 PM 398 Chapter 12 In a Windows application, you always know which window you’ll see first. A web application is a little different, because there are multiple points of entry. A user could surf to your site by typing a URL (or clicking an external link) that points to any page in your site. Similarly, when you debug your application, you can start running any page you want to test. All you need to do is select that page in the Solution Explorer before you run the application. Visual Studio’s behavior changes if you don’t select a web page (for exam- ple, if you select the application name or another file that can’t be executed, like the web.config settings file, in the Solution Explorer). In this case, Visual Studio runs the Default.aspx page (if your website includes it). If your website doesn’t have a Default.aspx page, the integrated web server in Visual Studio generates a list of all files in your web application (see Figure 12-7). You can then click any .aspx page to launch it. Figure 12-7: The file list for a web application with one web page TIP Because the compilation model is for a web application is different from that for other types of applications, you can’t use run-edit-continue debugging. Although you can make changes at debug time, the new code won’t be used automatically. But there is one shortcut available. After you make changes, you can start working with the new version of a web page by saving the file (in Visual Studio) and then clicking the Refresh button in your web browser. When you run a page, ASP.NET compiles the code in your page behind the scenes, runs it, and then returns the final HTML to the browser. Of course, the MetricConverter page doesn’t actually do anything yet, but you can still launch it and see all its controls. Adding an Event Handler Using Visual Studio, you can create event handlers for web forms exactly as you do in the Windows Form Designer (see Chapter 4 if you need a refresher). For example, you can add a Click event handler to the button bvb_02.book Page 398 Thursday, March 30, 2006 12:39 PM Web Forms and ASP.NET 399 in the MetricConverter program by double-clicking the button. Add the follow- ing code. (You may have to make slight modifications, depending on the names that you have given your controls.) Protected Sub cmdConvert_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdConvert.Click Dim Inches, Meters As Single Inches = 36 * Val(txtYards.Text) + 12 * Val(txtFeet.Text) Meters = Inches / 39.37 lblResult.Text = "Result in meters: " & Meters.ToString() End Sub You can now try running the program. Enter some sample values and click the Convert button. The label will be refreshed with the result of the conversion (see Figure 12-8). Figure 12-8: Testing a web page How Does It Work? What happens in our MetricConverter program is relatively simple: The server delivers an HTML page with a form submission button to your browser. When you click the button, the information entered by the user is transmitted back to the server, your code runs, and a new version of the page is delivered in response. This entire process unfolds automatically. Every time a user interacts with a control that fires an event, a similar “round trip” occurs from the client to the server and back. This round trip is called a postback. When you run a web page, you’ll notice that the URL in the browser includes a port number. For example, in Figure 12-8 you can see that run- ning the page named MetricConverter.aspx in a folder on my computer named TestWebSite displays the URL http://localhost:2414/TestWebSite/ MetricConverter.aspx. The localhost part at the beginning of the URL indicates that the web server is running on your computer. The port number (in this case, 2414) is randomly chosen every time Visual Studio starts the web bvb_02.book Page 399 Thursday, March 30, 2006 12:39 PM 400 Chapter 12 server, which ensures that web server requests won’t conflict with any other applications that might be running on your computer and listening for network communication. NOTE When you deploy a website you won’t need to use a port number to access it. That’s because the IIS web server listens to port 80, which is the official port for all HTTP traffic. When a URL doesn’t have a port number, port 80 is assumed by default. The AutoPostback Property The button we’ve created is a special type of control that will always cause a postback when clicked. Other controls are not as straightforward. For exam- ple, consider the TextChanged event of a TextBox control. In the MetricConverter program, we don’t use this event. However, another program might update the display dynamically as new text is entered, or as CheckBox or RadioButton controls are selected by the user. In this case, you would need to set the AutoPostback property for each of these controls to True. Because a postback involves getting a new page from the server, it can slow things down a little, and the user may notice the page flicker as it is being refreshed. For that reason, the default AutoPostback setting is False. When AutoPostback is disabled, the control’s events will be delayed until another control (like a button) triggers a postback. Thus, the code in the control’s event handler will not execute immediately. Web Control Events Events in web form controls are slightly different from Windows Forms controls. For example, the CheckedChanged event occurs when a RadioButton selection is changed, not necessarily every time it is clicked. Similarly, the TextBox event occurs when a user moves to a different control on the page after modifying the text box, not every time he or she presses a key. These changes are designed to minimize the number of postbacks. If a postback occurred every time the user pressed a key in a text box, the web page would be constantly reloading, the user would quickly become frustrated, and the web developer responsible would need to find a new line of employment. For similar reasons, events such as MouseMove and KeyPress aren’t implemented at all. In our MetricConverter example, we can leave AutoPostback set to False for all our controls, because a postback is triggered when the user clicks the button. A Web Form “Under the Hood” Here’s an interesting question: What’s the difference between Visual Basic 2005 and ASP.NET? The answer is that ASP.NET defines the markup language you use to design your web pages. Ordinarily, you can rely on Visual Studio to help you out here, and simply drag-and-drop your way to success. However, bvb_02.book Page 400 Thursday, March 30, 2006 12:39 PM [...]... do so, click the Source button at the bottom of the web form display Figure 1 2 -9 shows a portion of the ASP .NET markup that defines the controls and layout for the MetricConverter page, with one of the control tags highlighted You can click the Design button to switch back to the graphical designer view Figure 1 2 -9 : ASP .NET control tags for the MetricConverter page Here’s a sample ASP .NET control tag:... browser menu to see the HTML your browser received Figure 1 2-1 0 shows a portion of the HTML output that ASP .NET sends to the client for the MetricConverter page It’s similar to but different from the original ASP .NET tags, which can only be understood by the ASP .NET engine and not by ordinary Internet browsers Figure 1 2-1 0: HTML output for the MetricConverter The best part about all of this is that you... refer to another web page at all Instead, you need to redirect the user to the right page There are two basic ways to navigate to another page: Use the HyperLink web control Use the built in Redirect() method of the built in Response object, as in Response.Redirect("WebPage2.aspx") 408 C h ap te r 1 2 bvb_02 .book Page 4 09 Thursday, March 30, 2006 12: 39 PM Because the new web form will be in the same directory... built-in objects come from To get the lowdown on exactly how this works, you need to know a little bit about the object-oriented internals of an ASP .NET application All the built-in objects are provided through references in the System.Web.UI.Page class, which is the basis for every ASP .NET page, as shown in Figure 1 2-1 3 The Page class is fully described in the NET class reference included in the Visual. .. used The end of this chapter includes some helpful web links to live examples of web services New in NET Web services appeared in the VB toolkit for the first time in NET 1.0 However, they are still usable (with a little more work) in classic VB 6 The difference is that in previous version of VB you needed to use a separate component, named the Microsoft SOAP Toolkit, to get web service features For. .. 2006 12: 39 PM 3 4 Set the ProviderName property to the name of the ADO .NET provider you want the data source to use You can use System.Data.SqlClient for the SQL Server provider, System.Data.OracleClient for Oracle, or System.Data.OleDb for the OLE DB provider The next step is to supply the required connection string through the ConnectionString property 5 Now you need to define the query that the SqlDataSource... bvb_02 .book Page 422 Thursday, March 30, 2006 12: 39 PM Figure 1 2-1 8: The Virtual Directory Creation Wizard 5 The final wizard window gives you the chance to configure the permissions for the directory (Figure 1 2-1 9) The default settings allow clients to read the directory and run ASP .NET pages, but not to make any modifications This is the recommended configuration Figure 1 2-1 9: Virtual directory access permissions... Sub Other Controls As with the Windows Forms engine, Microsoft provides a full complement of controls for web forms Table 1 2-1 provides a quick overview of some of the most useful controls in the Standard tab Thinking About State There is one area where web programming is completely unlike Windows programming HTTP, the protocol used to communicate over the Internet, is stateless, which means that the. .. most VB developers, NET is the first time they’ll encounter web services In fact, web services are so well integrated into NET that they are sometimes identified synonymously with the entire NET platform Of course, now that you have read Chapter 1 of this book, you know what NET is really about—a compatible set of retooled languages, a runtime that provides high-level services, and a rich toolkit of. .. Studio 2005 Visual Studio Tools Visual Studio 2005 Command Prompt), and then type this: aspnet_regiis.exe -i The aspnet_regiis tool will update IIS by registering the ASP .NET file types Figure 1 2-1 6: Installing IIS Virtual Directories By default, your website’s home directory is the physical directory c:\ Inetpub\wwwroot, and the localstart.asp file is contained in this directory If you try to double-click . look under the hood. To do so, click the Source button at the bottom of the web form display. Figure 1 2 -9 shows a portion of the ASP .NET markup that defines the controls and layout for the MetricConverter. about the HTML details, and it’s the approach used in this chapter. bvb_02 .book Page 392 Thursday, March 30, 2006 12: 39 PM Web Forms and ASP .NET 393 Figure 1 2-3 : Adding a web form TIP The Select. Windows form. ASP .NET provides this kind of magic by using server-side controls. The basic idea behind a server-side control is that the display of the control is sent to the user in HTML, but the

Ngày đăng: 13/08/2014, 08:21

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

Tài liệu liên quan