Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
20
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

10

Componentization

Programming has been through several distinct phases in its history and has moved a long way from its humble beginnings where punch-cards dashed with holes were placed into mechanical readers. Early programs on PCs were often just sequential lines of Do A, Do B, Do C kinds of commands. If you wanted to repeat a section of the code, you were left with the option of going Do A, Do A, and Do A or encasing it in a loop and telling the PC to Do A 20 times. This quickly made code repetitive and unwieldy. Worse than that, it made it hard to follow, even for the people who had written it. To follow the flow from the beginning of a program to the end was as difficult as following the path of one thread of spaghetti on a plate in a mound of food. In fact, it became commonly known as spaghetti-coding!

Over the past 20 years there has been a move away from this kind of coding to a more object-based approach. This is where you break down the design of an application into a series of objects, and then any time you require an object, you just call it whenever you need it. This process is known as componentization. This is the creation of small objects, or components, that are self-contained parcels of code that have specific functions and are only called by the main application when needed. You looked at objects in Chapter 9 and saw how they could be mapped onto real-life counterparts to make coding less abstract. However, objects didn’t totally solve the problems with spaghetti-coding.

Classic ASP suffered from this malaise as well, and despite having a whole series of objects such as Response, Request, and Server, and also allowing users to create their own objects, ASP pages are still a nightmare to debug and follow if they get too big. In fact, three main problems can be highlighted, the first being that HTML code and ASP code tended to be dumped in the same page together, despite having completely different purposes. HTML manages the structure of the

page, whereas ASP is concerned with what the page does. The second problem is that with any kind of data handling in a page, there are two different purposes being dealt with, the connecting to and management of data stores, and the reading and writing of the data itself to a data source. The third problem is that of code-reuse, how users could easily create portable objects that could be called from within the code over and over, and how they could end up reducing the amount of code needed.

Chapter 10

With ASP.NET 1.x these problems were partially addressed; however, the solutions weren’t perfect. ASP.NET 2.0 delivers the most comprehensive set of solutions to these problems; indeed, at the design previews the ASP.NET development team openly boasted that ASP.NET 2.0 meant a 70% reduction of code in your pages. This chapter looks at the following topics:

Separation of code and content

Code-behind

Data layers

User controls

You’ve already looked at a lot of the new controls that are designed for every aspect of a web site, but now you’re going to dig behind the scenes and see how ASP.NET 2.0 also makes life easier for the developer with separation of code from content, data layers, and user controls.

The Separation of Code from Content

The funny thing with most text books that you pick up about a new technology is that they’ll quite happily tell you what was wrong with the old one, but not a lot about shortcomings in the new. Time and time again you’ll probably come across a variation on the same theme: the code of the page should be separated from the style and design of the page. It happened in HTML, it happened in classic

ASP, and it still happened to some extent in ASP.NET 1.x, although with a little care and effort it was possible to eliminate. With each new release you get a bit closer to achieving that lofty ambition. Before describing what ASP.NET 2.0 can offer to improve upon this, you need to know the answer to the question, “What is the separation of code from content, and why do you need to do it?

Let’s start with the first part, but first, I will digress a little. In most walks of life it’s possible for a person to wear many hats at the same time, thus you’ll find builders who can do carpentry, actors who think they can write, bus drivers who think they could drive a racing car; the list goes on. The truth is while most people’s skills are spread across a fairly wide area, they’re only likely to be able to specialize or be an expert in one or two areas at most. With programming, it’s common to find designers, administrators, and programmers lumped in together. In fact, in recent years “web site developer” has become a bit of an insult, meaning someone who can’t really design, can’t really program, and would struggle to administer a database as well. In fact, I’ve seen several job advertisements where the time-honored “time wasters need not apply” has been replaced by the 21st-century version “web developers need not apply!”

You might well be thinking at this point, “Hang on, I want to be a web developer, what’s wrong with that?” Well behind the seeming insult is a more serious point: A web developer is usually the person who has to spread himor herself thinly across three related but really quite different disciplines. The old cliché “jack of all trades, master of none” springs to mind. One of the reasons why they’ve had to do this is because the technologies involved (in this case ASP) have forced all three disciplines into one web page. So within your ASP page you would have to place the controls, have to implement the design, have to stick the code to make it work, and that code would more likely than not reference the database. Classic ASP was very easy to learn and pick up and hence people could get away with doing this kind of thing, but the truth is a lot of early ASP sites were very ugly, took ages to access the database, and were quite often buggy.

350

Componentization

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 design 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 separating the design from the code. In other words, the positioning of the ASP.NET controls would still be the remit 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=”VB”> Sub Form Page_Load()

If Page.IsPostback=true then Label1.Text = “Hello” + textbox1.Text

End If

End Sub </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 sample page is purely concerned with the design and structure of the page. For instance, you could move the label and textbox and button around, and the program would still work perfectly. However, if you messed with the order of the second page, everything would come to a jarring halt.

351

Chapter 10

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 separating 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 developer 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 alongside until they are needed, although when you select a Create Web Site option, a Default.aspx page and the corresponding code-behind Default.aspx.vb 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.

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.

The code is stored in a separate file, which is identified by a .vb suffix or (if you’re using C#) a .cs suffix. So if you created a Default.aspx page, then the code-behind file for that page would be called Default.aspx.vb. Not all languages in the .NET Framework actually 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 9 when you learned about the idea of using inheritance 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 once again, but this time from a slightly different angle:

<%@Page Language=”VB” CodeFile=”Default.aspx.vb” Inherits=”_default”%>

You’re interested in two particular attributes of Page, namely Inherits and CodeFile.

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.

352

Componentization

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 specify 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 once you’ve added these two attributes, next you need to create the code-behind file itself.

Partial Classes

If you check the contents of a typical code-behind file, and you can do this by creating a new ASP.NET web site and then viewing the contents of Default.aspx.vb, which is created automatically, you will see the following three lines:

Partial Class _Default

Inherits System.Web.UI.Page

...

End Class

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 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 compilation 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 (see the following code) that occurs when the page is first loaded up:

Sub Page_Load (ByVal Sender As Object, ByVal e as EventArgs) Handles Me.Load

...

End Sub

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

353

Chapter 10

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 working 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, too, namely single-file pages are easier to send to another programmer because there is only one file, they’re also 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 a TextBox, Button, and Label control. 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.

354

Componentization

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.vb (refer to Figure 10-1).

Once again I stress that 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.

3.Go back to the Default.aspx file first and add two Label controls, a TextBox control, and a Button control, as shown in Figure 10-2.

Figure 10-2

355

Chapter 10

You’ll need to 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) Then

If TextBox1.Text = “42” Then

Label2.Text = “So you read Douglas Adams as well...”

Else

Label2.Text = “No, I’m not sure that’s it”

End If

End If

356

Componentization

6.Click the green arrow to run it and 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 separate 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 had already been created:

<%@Page ... CodeFile=”Default.aspx.vb” Inherits=”_Default” %>

This refers to the code-behind file Default.aspx.vb. 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) Then

If TextBox1.Text = “42” Then

Label2.Text = “So you read Douglas Adams as well...”

Else

Label2.Text = “No, I’m not sure that’s it”

End If

End If

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 accordingly. 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.

Compilation in ASP.NET 2.0

Compilation is another one of those subjects that I don’t really want to go into in depth, because you don’t need to know too much about it, however you should be aware of its presence. What happens when you submit your Web Form to the server is that your Web Form and ASP.NET pages first have to

357

Chapter 10

be translated into a language the server can understand. This is known as compilation. You how this process works in .NET 2.0 in Figure 10-5.

Disk

ASP.NET page

Compiler

 

.NET CLR

Runtime

Intermediate Code

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 (Page.IsPostBack)

Your code can be compiled in two ways:

Pre-Runtime Compilation: Normal (the “old way,” the default way in ASP.NET 1.1) — Codebehind files are compiled into an assembly and stored in the \bin directory. Web Forms and

.aspx pages are compiled when needed.

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.

358