Websites and Web Projects
Somewhat confusingly, Visual Studio offers two ways to create an ASP.NET-powered web application:
• Project-based development: When you create a web project, Visual Studio generates a .csproj project file (assuming you’re coding in C#) that records the files in your project and stores a few debugging settings. When you run a web project, Visual Studio compiles all your code into a single assembly before launching your web browser.
• Projectless development: An alternate approach is to create a simple website without any project file. In this case, Visual Studio assumes that every file in the website directory (and its subdirectories) is part of your web application. In this scenario, Visual Studio doesn’t need to precompile your code. Instead, ASP.NET compiles your website the first time you request a page. (Of course, you can use precompilation to remove the first-request overhead for a deployed web application.)
The first .NET version of Visual Studio used the project model. Visual Studio 2005 removed the project model in favor of projectless development. However, a small but significant group of developers revolted. Realizing that there were specific scenarios that worked better with project-based development, Microsoft released a download that added the project feature back to Visual Studio 2005. Now, both options are supported in Visual Studio 2008.
Create a Projectless Website
THE HIDDEN SOLUTION FILE
Although projectless development simplifies life, the last vestiges of Visual Studio’s solution-based system are still lurking behind the scenes. When you create a web application, Visual Studio actually creates solution files (.sln and .suo) in a user-specific directory. In Windows Vista, this is a directory like c:\Users\[UserName]\Documents\Visual Studio 2008\Projects\ [WebsiteFolderName]. In earlier versions of Windows, it's a directory like c:\Documents and Settings\[UserName]\ My Documents\Visual Studio 2008\Projects\[WebSiteFolderName].
The solution files provide a few Visual Studio–specific features that aren’t directly related to ASP.NET, such as debugging settings. For example, if you add a breakpoint to the code in a web page, Visual Studio stores the breakpoint in the .suo file. The next time you open the website, Visual Studio locates the matching solution files automatically. Similarly, Visual Studio uses the solution files to keep track of the files that are currently open in the design environment so that it can restore your view when you return to the website.
This approach to solution management is fragile—obviously, if you move the website from one location to another, you lose all this information. However, because this information isn’t really all that important (think of it as a few project-specific preferences), losing it isn’t a serious problem. The overall benefits of a projectless system are usually worth the trade-off. If you want a more permanent solution, you can save your solution files explicitly in a location of your choosing. To do so, simply click the top item in the Solution Explorer (which represents your solution). For example, if you open a folder named MyWebSite, the top item is named Solution 'MyWebSite'. Then, choose File ➤ Save [SolutionName] As. This technique is handy if you’ve created a solution that combines multiple applications (for example, a projectless website and a class library component) and you want to edit and debug them at the same time.
Multitargeting
Previous versions of Visual Studio were tightly coupled to specific versions of .NET. You used Visual Studio .NET to create .NET 1.0 applications, Visual Studio .NET 2003 to create .NET 1.1 applications, and Visual Studio 2005 to create .NET 2.0 applications.
Visual Studio 2008 removes this restriction. It allows you to create web applications that are designed to work with .NET 2.0, .NET 3.0, or .NET 3.5. As you learned in Chapter 1, all three of these versions of .NET actually use the same ASP.NET 2.0 engine (and version 2.0 of the CLR). That means that a server that only has .NET 3.5 can run an ASP.NET 2.0 application without a hitch.
Visual Studio .NET -------- .NET 1.0 applications
Visual Studio .NET 2003 -------- .NET 1.1 applications
Visual Studio 2005 -------- .NET 2.0 applications
Visual Studio 2008 -------- .NET 2.0, .NET 3.0, .NET 3.5 (all based on ASP.NET 2.0 engine)
You can also change the version you’re targeting at any point afterward by following these steps:
1. Choose Website ➤ Start Options. 2. In the list on the left, choose the Build category. 3. In the Target Framework list, choose the version of .NET you want to target.
When you change the .NET version, Visual Studio modifies your web.config file. The web.config file for a .NET 2.0 or .NET 3.0 application is nearly empty. But the web.config file for a .NET 3.5 application includes a good deal of extra boilerplate to support Ajax and C# 3.5.
web.config for .NET 2.0 application ---- nearly empty
web.config for .NET 3.0 application ---- nearly empty
web.config for .NET 3.5 application ---- lots of content to support Ajax and C# 3.5
The Code Model
Visual Studio supports two models for coding web pages:
Inline code: This model is the closest to traditional ASP. All the code and HTML markup is stored in a single .aspx file. The code is embedded in one or more script blocks. However, even though the code is in a script block, it doesn’t lose IntelliSense or debugging support, and it doesn’t need to be executed linearly from top to bottom (like classic ASP code). Instead, you’ll still react to control events and use subroutines. This model is handy because it keeps everything in one neat package, and it’s popular for coding simple web pages.
Code-behind: This model separates each ASP.NET web page into two files: an .aspx markup file with the HTML and control tags, and a .cs code file with the source code for the page (assuming you’re using C# as your web page programming language). This model provides better organization, and separating the user interface from programmatic logic is keenly important when building complex pages.
In Visual Studio, you have the freedom to use both approaches. When you add a new web page to your website (using Website ➤ Add New Item), the Place Code in a Separate File check box lets you choose whether you want to use the code-behind model. Visual Studio remembers your previous setting for the next time you add a new page, but it’s completely valid (albeit potentially confusing) to mix both styles of pages in the same application. This flexibility only applies to projectless development. If you’ve created a web project, you must use the code-behind model—there’s no other choice. Furthermore, the code-behind model is subtly different for the code-behind model that’s used in a projectless website, as you’ll see shortly.
Web Site (projectless) can have both 2 code model, while web project only can have Code-behind model.
1. How Code-Behind Files Are Connected to Pages
Every .aspx page starts with a Page directive. This Page directive specifies the language for the page, and it also tells ASP.NET where to find the associated code (unless you’re using inline code, in which case the code is contained in the same file).
Your .aspx page uses the Inherits attribute to indicate the class you’re using, and the CodeFile attribute to indicate the file that contains your code-behind, as shown here:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="TestFormCodeBehind.aspx.cs"
Inherits="TestFormCodeBehind"%>
2. How Control Tags Are Connected to Page Variables
When you request your web page in a browser, ASP.NET starts by finding the associated code file. Then, it generates a variable declaration for each server control (each element that has the runat="server" attribute).
For example, imagine you have a text box named txtInput:
<asp:TextBox />
ASP.NET generates the following member variable declaration and merges it with your page class using the magic of partial classes:
protected System.Web.UI.TextBox txtInput;
Of course, you won’t see this declaration, because it’s part of the automatically generated code that the .NET compiler creates. But you rely on it every time you write a line of code that refers to the txtInput object (either to read or to write a property):
txtInput.Text = "Hello.";
To make sure this system works, you must keep both the .aspx markup file (with the control tags) and the .cs file (with the source code) synchronized.
If you edit control names in one piece using another tool (such as a text editor), you’ll break the link, and your code won’t compile. Incidentally, you’ll notice that control variables are always declared with the protected accessibility keyword. That’s because of the way ASP.NET uses inheritance in the web-page model. The following layers are at work:
1. The Page class from the .NET class library defines the basic functionality that allows a web page to host other controls, render itself to HTML, and provide access to the traditional ASPstyle objects such as Request, Response, and Session. 2. Your code-behind class (for example, TestFormCodeBehind) inherits from the Page class to acquire the basic set of ASP.NET web-page functionality. 3. When you compile your class, ASP.NET merges some extra code into your class (using the magic of partial classes). This automatically generated code defines all the controls on your page as protected variables so that you can access them in your code. 4. The ASP.NET compiler creates one more class to represents the actual .aspx page. This class inherits from your custom code-behind class (with the extra bit of merged code). To name this class, ASP.NET adds _aspx to the name of the code-behind class (for example, TestFormCodeBehind_aspx). This class contains the code needed to initialize the page and its controls and spits out the final rendered HTML. It’s also the class that ASP.NET instantiates when it receives the page request.
So, why are all the control variables and methods declared as protected? It’s because of the way inheritance is used in this series of layers. Protected variables act like private variables, with a key difference—they are accessible to derived classes. In other words, using protected variables in your code-behind class (for example, TestFormCodeBehind) ensures that the variables are accessible in the derived page class (TestFormCodeBehind_aspx). This allows ASP.NET to match your control variables to the control tags and attach event handlers at runtime.
3. How Events Are Connected to Event Handlers
Visual Studio 2008 uses automatic event wire-up, as indicated in the Page directive. Automatic event wire-up has two basic principles:
• All page event handlers are connected automatically based on the name of the event handler. In other words, the Page_Load() method is automatically called when the page loads. • All control event handlers are connected using attributes in the control tag. The attribute has the same name as the event, prefixed by the word On.
For example, if you want to handle the Click event of the Button control, you simply need to set the OnClick attribute in the control tag with the name of the event handler you want to use.
Here’s the change you need: <asp:Button >
ASP.NET controls always use this syntax. Remember, because ASP.NET must connect the event handlers, the derived page class must be able to access the code-behind class. This means your event handlers must be declared with the protected or public keyword. (Protected is preferred, because it prevents other classes from seeing this method.)
Of course, if you’re familiar with .NET events, you know there’s another approach to connect an event handler. You can do it dynamically through code using delegates. Here’s an example: cmdOK.Click += cmdOK_Click;
--------------------- So far, all the thing is about Projectless Web Sites appliation-------------------
Web Projects
So far, you’ve seen how to create websites without any project files. The advantage of projectless development is that it’s simple and straightforward. When you create a projectless website, you don’t need to deploy any extra support files. Instead, every file in your web folder is automatically considered part of the web application. (This model makes sense because every web page in a virtual directory is independently accessible, whether or not you consider it an official part of your project.)
Projectless development remains popular for the following reasons:
Projectless development simplifies deployment: You simply need to copy all the files in the website directory to the web server—there aren’t any project or debugging files to avoid.
Projectless development simplifies file management: If you want to remove a web page, you can simply delete the associated files using the file management tool of your choice. If you want to add a new page or move a page from one website to another, you simply need to copy the files—there’s no need to go through Visual Studio or edit the project file. You can even author web pages with other tools, because there’s no project file to maintain.
Projectless development simplifies team collaboration: Different people can work independently on different web pages, without needing to lock the project files.
Projectless development simplifies debugging: When creating a web project, you must recompile the entire application when you change a single page. With projectless development, each page is compiled separately, and the page is only compiled when you request it for the first time.
Projectless development allows you to mix languages: Because each web page is compiled separately, you’re free to code your pages in different languages. In a web project, you’d be forced to create separate web projects (which is trickier to manage) or separate class library projects.
That said, there are some more specialized reasons that might lead you to adopt project-based development instead, or use web projects in specific scenarios.
Project-Based Development
When you create a web project, Visual Studio generates a number of extra files, including the .csproj and .csproj.user project files and a .sln solution file. When you build your application, Visual Studio generates temporary files, which is places in the Obj subdirectory, and one or more .pdb files (in the Bin subdirectory) with debugging symbols. None of these files should be deployed to the web server when your web application is complete. Furthermore, none of the C# source code files (files with the extension .cs) should be deployed, because Visual Studio precompiles them into a DLL assembly.
Project-Based Development Advantages
Project-based development has a dedicated following. The most significant advantages to web projects are the following:
The project development system is stricter than projectless development: This is because the project file explicitly lists what files should be part of the project. This allows you to catch potential errors (such as missing files) and even deliberate acts of sabotage (such as unwanted files added by a malicious user).
Web projects allow for more flexible file management: One example is if you’ve created several separate projects and placed them in subdirectories of the same virtual directory. In this case, the projects are kept separate for development purposes but are in essence the same application for deployment. With projectless development, there’s no way to keep the files in these subdirectories separate.
Web projects allow for a customizable deployment process: Visual Studio project files work with the MSBuild utility, which allows project compilation to be automated and customized. Also, you get more control over the generated assembly for your web application, which you can name appropriately, sign, and so on.
Web projects work better in some migration scenarios: For this reason, ASP.NET automatically converts Visual Studio .NET 2003 web projects to Visual Studio 2008 web projects. This conversion requires fewer changes to your pages.
Differences between Projectless Websites and Web Projects
• Compilation: As explained earlier, web projects are compiled by Visual Studio (not ASP.NET) when you run them. The web page classes are combined into a single assembly that has the name of the web project (like WebApplication1.dll), which is then placed in the Bin folder.
• Code-behind: The web pages in a web project always use the code-behind model. However, they include an extra file with the extension .aspx.desginer.cs, which includes the declarations for all the controls on the web page. This means if you create a page named Default.aspx, you’ll end up with a code-behind class in a file named Default.aspx.cs and control declarations in a file named Default.aspx.designer.cs. At compile time, these two files will be merged. In a projectless website, you never see a file with the control declarations, because this part of the code is generated at compile time by ASP.NET.
• The Page directive: The web pages in a web project use a slightly different Page directive. Instead of using the CodeFile attribute to indicate the file that has the source code, they use the CodeBehind attribute. This difference is due to the fact that Visual Studio performs the compilation instead of ASP.NET. ASP.NET checks the CodeFile attribute, but Visual Studio uses the CodeBehind attribute.
• Assembly references: In a projectless website, all the assembly references are recorded in the web.config file, so ASP.NET can use them when resolving references at compile time. But the assembly references in a web project are stored in a project file, which Visual Studio uses when it compiles the code. The only exceptions are the references to the System.Core.dll and System.Web.Extensions.dll assemblies, which contain all the features that are specific to .NET 3.5. These references are defined in the web.config file because they include classes that you need to specify new configuration settings.
■Note The code file with the control declarations isn’t available in a projectless web application. Instead, it’s generated behind the scenes the first time the application is compiled and executed. As a result, you never have the chance to view this code.
|
请发表评论