BeginningASP.NET 2.0 with C# PHẦN 6 pot

76 376 0
BeginningASP.NET 2.0 with C# PHẦN 6 pot

Đ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

Consider this scenario: What happens if your boss tells a designer to change the font on the web site, while telling the developer to add a search text box to the front page to search on the contents of the site? In times gone by, both people would be scrambling for the same page to make the alterations. Worse still, the designer could do his version of index.asp, while the programmer could do his, and therefore neither version would please the boss. Even if they did it sequentially, quite often the programmer would mess up the pristine design, or the designer would break a vital piece of code. I’m not intending to patronize either job; this has honestly happened on projects I’ve worked on. It therefore makes more sense to have two different versions of the same page. And it makes sense to let the designer with his graphic design and art qualifications do the interface of the web site, with the programmer at the back end connecting all the bits of the site and making them work. This is where separating the code from the content comes in. In this fictitious scenario, you’d probably use Cascading Style Sheets to get around the problem. However, you’d still have the problem of the sep- arating the design from the code. In other words, the positioning of the ASP.NET controls would still be the responsibility of the programmer. ASP.NET 2.0 goes beyond the separation of code from content. The Separation of Code from Design So far you’ve read about two distinct areas in ASP.NET 2.0, the first being the HTML code and ASP.NET controls, which you can see in this sample page: <html> <head> </head> <body> <form runat=”server”> <aspnet:label id=”label1” runat=”server” text=”Enter your name:”><aspnet:label> <aspnet:textbox id=”textbox1” runat=”server”></aspnet:textbox> <aspnet:button id=”button1” runat=”server” text=”submit”> </form> </body> </html> The second is the actual code, which is placed within the <head> tags of the first: <script language=”C#”> private void Page_Load(object sender, EventArgs e) { if (Page.IsPostback==true) { Label1.Text = “Hello” + textbox1.Text; } } </script> This layout is known as the single-file scenario. This chapter uses the term “single-file” when talking about putting the code within <script> tags on the page. The first section of code in the single-file sam- ple page is purely concerned with the design and structure of the page. For example, you could move 349 Componentization 13_042583 ch10.qxd 4/4/06 2:48 PM Page 349 the label and textbox and button around, and the program would still work perfectly. However, if you altered the order of the second section of code, everything would come to a jarring halt. Worse still, behind the scenes the single-file scenario actually created far more work than was necessary. A second scenario is a little sidebar that displays a shopping basket as you browse around the site. How would you do it? Would you have to add this code to every single page? If you added it to every page, would you have to update every single page, every time you made a change? A sensible strategy of sep- arating content from code, data from code, and being able to reuse the code is obviously needed. So let’s start by looking at the first point in this three-pronged strategy. Code-Behind Code-behind is simply a separate code file linked to your Web Form or .aspx page. You place all of your HTML tags and ASP.NET controls in the .aspx page, and you have a separate page “behind” this page that contains all of the code that is normally contained within the <script> blocks for the page. So to answer the designer/developer dilemma, your designer can update the .aspx page, while your devel- oper can update the code-behind page. Code-behind pages are very easy to use. Like their .aspx counterparts, they are composed of pure text and can be viewed in Visual Web Developer, Notepad, or any text editor. The .aspx is the centerpoint, and the code-behind is like an attachment. In Visual Web Developer, code-behind pages are not created until they are needed, although when you select a Create Web Site option, a Default.aspx page and the corresponding code-behind Default.aspx.cs are created automatically. However, for any further pages that you create, only the .aspx page is added, unless you check the Place Code in Separate File option, which is unchecked by default. The code is stored in a separate file, which is identified by a .cs suffix or (if you’re using VB.NET) a .vb suffix. So if you created a Default.aspx page, the code-behind file for that page would be called Default.aspx.cs. Not all languages in the .NET Framework support the code-behind model, most notably J#, but the two main languages that most developers use and the only two considered in this book both use code-behind. The Page Directive You’ve already met the Page directive in Chapter 5 when you learned about the idea of using inheri- tance with the .NET Framework, to inherit certain features from classes. The Page directive also refers to where your separate code-behind file is stored. Look at the same directive and the same attributes again, but this time from a slightly different angle: <%@Page Language=”C#” CodeFile=”Default.aspx.cs” Inherits=”_default”%> This runs contrary to what happens in Visual Studio .NET 2005, where when you create a new Web Form, a new code-behind file is automatically created at the same time. 350 Chapter 10 13_042583 ch10.qxd 4/4/06 2:48 PM Page 350 You’re interested in two particular attributes of Page: ❑ Inherits: This attribute tells you which class you want to inherit from. It’s vital that the Inherits attribute matches a class in the code-behind file. ❑ CodeFile: This attribute specifies the name of the code-behind file. Typically you would expect the code-behind file to be kept in the same folder, but it’s possible to keep it separate and spec- ify a URL inside this attribute as well. If you want to use code-behind, you must include these two attributes at all times. If you want to add a code-behind file manually to an .aspx file, then after you’ve added these two attributes, next you need to create the code-behind file itself. Partial Classes You can check the contents of a typical code-behind file by creating a new ASP.NET web site and then viewing the contents of Default.aspx.cs, which is created automatically. You will see the following three lines: partial class _Default : System.Web.UI.Page { } Any code you create should be placed within a partial class. Although this section won’t go into partial classes too much, it is necessary to talk a little about them. In the last chapter, you saw classes as being cookie cutters that define the shape of the cookies. So what is a partial class? Half a cookie cutter? Well in some ways, yes is the answer. If you’ve played around with ASP.NET 1.x at all, you’ll have noticed that there was a lot more than just three lines of code in the code-behind file, in the section marked Web Form Designer Generated Code. In the previous version of ASP.NET, if you stuck your control in the page, under certain conditions your code-behind file didn’t always see it. Partial classes mean that at compila- tion time, your code-behind file and the Web Form are now merged into one class file, thus making sure this kind of scenario didn’t happen. It also means you only need these three lines of code to make it work. So your code-behind file is one half of the cookie cutter and the Web Form is the other half, and together they make the whole. Let’s leave that analogy before it gets squeezed any more. Event Handlers/Functions You place the code in the partial class; however, this is not quite enough to make it work. The code also should be placed within an event handler or a subroutine or function of some sort. All code in ASP.NET is run in reaction to an event of some sort. If you don’t actually place your code in an event handler, you’ll probably need a call to your subroutine or function placed within an event handler. The most common one is the Page_Load event handler that occurs when the page is first loaded: private void Page_Load (object sender , EventArgs e ) { } 351 Componentization 13_042583 ch10.qxd 4/4/06 2:48 PM Page 351 Of course you don’t have to type this in —if you double-click the page in Design View, the Page_Load event handler will be added for you. This is just another good reason for using Visual Web Developer. In previous versions of this book, we’ve used humble Notepad as our editor to make changes to the code. This isn’t because we endorse a firmly Luddite/anti-progress view of the world, but because Notepad made no changes to our HTML code (unlike the majority of HTML editors), and because it is something everybody with a version of Windows automatically had. With code-behind, things become slightly more complex, in that you have two files that basically refer to the same page (see Figure 10-1). You can still of course manage them via Notepad, but the features in Visual Web Developer make it much easier to manage the two separate pages (and see them as connected entities). Figure 10-1 Of course, you might think, well why not stick with Notepad and also stick with the single-file model? The following list reiterates some of the advantages of using code-behind files: ❑ Separation of the content (user interface) from the code. It is practical to have a designer work- ing on the markup while a programmer writes code. ❑ Better security, because code is not exposed to the designers or others who are working only with the page content. ❑ Code can be easily reused for multiple pages. However, this doesn’t mean that code-behind is always the perfect solution to all your problems. Using a single file for your code and content is still the more sensible option within some scenarios: ❑ Single-file is best suited for pages where the code consists primarily of event handlers for the controls on the page. ❑ Where there is little code, it can be easier to view a single-file page because both the code and the HTML are in the same place. There are also some reasons of convenience to consider as well, namely single-file pages are easier to send to another programmer because there is only one file, they’re easier to rename, and managing files is slightly easier, because the page is self-contained in a single file, and there are therefore fewer pages to manage. Generally, though, you really should be placing your code in a separate code-behind file, because the advantages outweigh the disadvantages for the most part. Creating a Code-Behind File That’s enough talk. In the next Try It Out, you get down to the business of creating an incredibly simple code-behind file that interacts with a sample page containing TextBox, Button, and Label controls. 352 Chapter 10 13_042583 ch10.qxd 4/4/06 2:48 PM Page 352 You’ll see how you can manipulate all of these controls in the same way as you might expect to when using a single file. Try It Out Creating a Code-Behind File 1. Open VWD and create a new web site called TestCodeBehind in the Chapter directory ( C:\BegASPNET2\Chapters\Begin\Chapter10). 2. Go to Solution Explorer and click the plus symbol (+) next to Default.aspx to expand the tree to reveal the file Default.aspx.cs (refer to Figure 10-1). 3. Go back to the Default.aspx file and add two Label controls, a TextBox control, and a Button control, as shown in Figure 10-2. Figure 10-2 Again, Default.aspx is the only file that has the code-behind file automatically created for you. If you create another Web Form, you must make sure to check the Place Code in a Separate File option, which is unchecked by default. 353 Componentization 13_042583 ch10.qxd 4/4/06 2:48 PM Page 353 Adjust the source HTML to read as follows: <asp:Label ID=”Label1” runat=”server” Text=”What is the answer to the meaning of life, the universe and everything?:”></asp:Label> <br /><br /> <asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox> <br /><br /> <asp:Button ID=”Button1” runat=”server” Text=”Submit” /> <br /><br /> <asp:Label ID=”Label2” runat=”server” Text=””></asp:Label> 4. Go back to Design View and double-click anywhere on the background of Default.aspx other than on the controls. Doing so will open up into the code-behind file, shown in Figure 10-3. Figure 10-3 5. Add the following code to the Page_Load event handler: if (Page.IsPostBack) { if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”; else { 354 Chapter 10 13_042583 ch10.qxd 4/4/06 2:48 PM Page 354 Label2.Text = “No, I’m not sure that’s it”; } } 6. Click the green arrow to run it. You may get a textbox asking whether or not to add a new Web.config file or run without debugging. Click the former. 7. Enter a value or lengthier sentence into the text box, as shown in Figure 10-4. Figure 10-4 How It Works It all seems very simple —instead of putting your code within <script> tags, you place it within a sep- arate page, connected by the Page directive tag. Indeed, if you check at the top of the Source View for Default.aspx, you can see that the following was already created: <%@Page CodeFile=”Default.aspx.cs” Inherits=”_Default” %> This refers to the code-behind file Default.aspx.cs. There the following code is run when the Page_Load event is called (when the page is viewed). This is just the normal kind of code talked about in Chapter 9: if (Page.IsPostBack) { if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”; else { Label2.Text = “No, I’m not sure that’s it”; } } It says if the page has been posted back (submitted), check the contents of the TextBox control. If it equals 42, then you have your correct answer, and you set the Label2 control’s Text property accord- ingly. If the contents of the TextBox control do not equal 42, you display a different answer (“No, I’m not sure that’s it” ). However, there is a bit more going on beneath the covers, namely the method by which your code is compiled. 355 Componentization 13_042583 ch10.qxd 4/4/06 2:48 PM Page 355 Compilation in ASP.NET 2.0 Compilation is another one of those subjects that this book doesn’t go into in depth, because you don’t need to know too much about it. However, you should be aware of its presence. When you submit your Web Form to the server, your Web Form and ASP.NET pages first have to be translated into a language the server can understand. This is known as compilation. You can see how this process works in .NET 2.0 in Figure 10-5. Figure 10-5 The compiler changes your code into something known as intermediate code, or Microsoft Intermediate Language (MSIL). This language is something that is independent of any PC it is run on. The .NET CLR (Common Language Runtime) is able to take this intermediate code and change it into executable code that it can run and provide output for. The output is then sent back to the user as a response. (There’s actually a bit more to this process, as you’ll see in Chapter 14.) During the process of compilation, your pages are approved syntactically, so if you’ve made any typos such as the following, they will be spotted at compile time: if (Paige.IsPostBack) Your code can be compiled in two ways: ❑ Pre-Runtime Compilation: The “normal” way (or the “old way,” —the default way in ASP.NET 1.1). Code-behind files are compiled into an assembly and stored in the \bin directory. Web Forms and .aspx pages are compiled when needed. Disk Request ASP.NET page Compiler Intermediate Code Response .NET CLR Runtime 356 Chapter 10 13_042583 ch10.qxd 4/4/06 2:48 PM Page 356 ❑ Full Runtime Compilation: Code-behind files and any other associated code can now be placed in the App_Code folder. ASP.NET 2.0 will then create and maintain references to the assembly that is generated from these files at runtime. The App_Code Folder If you create an App_Code folder in your project, any code you place in that project will automatically be compiled when you run the project. It’s a far more robust solution than the old \bin folder used by ASP.NET 1.x, and for that reason you should use it for any code other than code-behind. The reason you should not use it for code-behind is that it is easier in VWD to keep your code files attached to the page they are related to; otherwise viewing them could be a pain. So not only can you organize your code and in which pages it is placed, but ASP.NET 2.0 dictates a different structure for ordering where those pages are placed. Data Layers You’ve looked at how code and content can be successfully separated, but there is a third dimension to our discussions, namely that of the data. Throughout this book, we’ve paused to reflect briefly on vari- ous aspects of the history of the Internet and the Web, while trying to keep you away from a huge lec- ture on the entire subject. However, another quick history lecture is in order here to help you understand the purpose of the next ASP.NET 2.0 feature. Two-Tier Applications Rather than rewinding too far back, let’s jump in halfway. When HTML started getting beyond the uni- versities, it became necessary to provide something more than just static text and images. One of the first ways in which web pages were made dynamic was to enable them to access a database. The browser was one tier, and the database was the second tier. In this scenario, the browser dealt with rules about the business or application and user interface. The data retrieval and manipulation was performed by another separate database application, such as SQL Server or Microsoft Access. It would handle the data storage and retrieval device for the applica- tion. These two-tier applications were also commonly know as client-server applications. A typical client- server application is depicted in Figure 10-6. The term business rules is used to encompass any part of the application logic that isn’t the user interface or the database. If the application isn’t being used for a busi- ness, then the term application logic might be more applicable, although they mean the same thing. There is actually a third option called deployment pre-compilation, which is for full compilation of your project prior to deployment. You’ll learn a little more about this in Chapter 16. 357 Componentization 13_042583 ch10.qxd 4/4/06 2:48 PM Page 357 Figure 10-6 The other popular variation on the two-tier application saw the business rules (application logic) being executed on the database system. Such applications would commonly use stored procedures to manipulate the database (or in some cases triggers). A stored procedure is a query that is stored on the database. It can be called by the client application and then run on the server. It would contain rules about the busi- ness as well. For example, if you had a league table on Wrox United that awarded three points for a win and one point for a draw, then in the database query, it would somehow have to record that when one side scores more goals than another side, it is worth three points. This is a business rule. It doesn’t mat- ter to the database how many points you add on to the win; however, your league table would fail to work properly if you added two or five points for a win. Three-Tier Applications The big difference with three-tier applications is that business rules are no longer located on either the client or the database. They are stored and run on a system in between the client and the server. The advantage of this is that the business rules server can ensure that all of the business processing is done correctly. There is now a third layer interface, business rules and data. The introduction of the data tier is illustrated in Figure 10-7. Figure 10-7 In a three-tier application, the client never accesses the data storage system directly. You can make changes to the business rules and this would mean you could change any part of the system without having to alter the other two parts. As the three different sections of the application communicate via interfaces, and as long as the interface between the code and application front-end remains the same, the internal workings of each part can be changed without affecting the rest of the application. The REQUEST RESPONSE RECORDS QUERY Client Server BUSINESS RULES Data Source REQUEST RESPONSE Client Server 358 Chapter 10 13_042583 ch10.qxd 4/4/06 2:48 PM Page 358 [...]... and set them as attributes, just like you would with a normal ASP.NET server control 367 Chapter 10 Login Control (ASP.NET) Link to ShoppingCart Control (User) Figure 10- 16 News Control (User) So why isn’t everything an ASP.NET server control? Well, ASP.NET 2.0 ships with a multitude of controls designed for the most common scenarios and situations ASP.NET 2.0 adds greatly to the number of server controls... the ObjectDataSource control The Common Tasks box appears with the words “Configure Data Source.” Click this 5 In the dialog box that appears, there is a single drop-down list asking you to choose your business object (see Figure 10-12) There should only be one, the odsTableAdapters PlayersTableAdapter Select it and click Next Figure 10-12 6 362 On the next screen (shown in Figure 10-13), under the... shouldn’t be interfering there at all So this brings you to the end of your little excursion, because you can now look at a new feature in ASP.NET 2.0 that allows you to separate your applications more simply into three tiers What’s New in ASP.NET 2.0 In ASP.NET 2.0, you are no longer restricted to binding only to data controls You can also bind to separate business controls via the ObjectDataSource control... using a Flash plug-in or a Java applet, you would see some indication with an tag or on older browsers, possibly an tag So there’s no worry about extra download time being taken either 368 Componentization Figure 10-17 If you look at the actual page that is sent to the server, you can see the user control is included with two simple lines of code that highlighted here (this source code... User controls are stored in separate files with a separate ascx extension Any time you see this extension, you know that you are dealing with a user control To create a user control, you need to add a @Register directive to the top of your Web Form identifying where you can find your user control: 369 Chapter 10 You need to add a new tag specifying... actually just custom controls that someone at Microsoft has already created for you and distributed with ASP.NET 2.0 A main difference between user controls and custom controls is that user controls are intended to be confined to the application they were created for, whereas custom controls can be used with any application Hence they are pre-compiled into assembly files, making them more portable They... file type The creation of custom controls is something you have to worry about less now, given the vast amount of controls provided with ASP.NET 2.0, and for that reason they are not covered in this book For in-depth discussion of custom controls, consult Professional ASP.NET 2.0 by Bill Evjen, et al, from Wrox Press Summar y This chapter has taken a slightly more theory-heavy slant than previous chapters,... controls For example, in ASP.NET 1.1 if you wanted a Login control, you had to stitch together a username text box, a password text box, a button, and a label for messages within a panel, so you had to create this as a user control In version 2.0, the Login control comes as a server control However, it just isn’t possible to anticipate everything that a user might want or need Therefore, it makes sense to... EditSquad.aspx, which is used to change the players’ details However, it uses the SqlDataSource control for the details This can be replaced with an ObjectDataSource control It has insert, update, select, and delete methods that map neatly to the methods in a simple class 364 Componentization Try It Out The Wrox United ObjectDataSource 1 Open the Wrox United application from the chapter samples (C:\BegASPNET2\Chapters\... DetailsDataSource_Inserted(object sender , System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs } protected void DetailsDataSource_Deleting(object sender , System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs { } 366 e) e) As e) Componentization 21 22 Save and close the file Run the application, log in as an administrator (dave\dave@123), and navigate to the EditSquad.aspx page It works in the same way as before . As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs e) { } 366 Chapter 10 13 _0 425 83 ch 10. qxd 4/4 / 06 2: 48 PM Page 366 21 . Save and close the file. 22 . Run the application, log in as an administrator (davedave@ 123 ), and navigate to. control. 367 Componentization 13 _0 425 83 ch 10. qxd 4/4 / 06 2: 48 PM Page 367 Figure 10- 16 So why isn’t everything an ASP .NET server control? Well, ASP .NET 2. 0 ships with a multitude of con- trols designed. Use SQL statements radio button (as shown in Figure 10- 9) and click Next. Figure 10- 9 3 60 Chapter 10 13 _0 425 83 ch 10. qxd 4/4 / 06 2: 48 PM Page 3 60 8. On the next wizard screen, you can define the

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

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan