Create an ASP.NET Project

 

Create an ASP.NET Project

Let's go further and create a sample ASP.NET project with Visual Studio .NET 2005. You first create a new Web site by choosing the corresponding command on the File|New menu. The dialog box that appears prompts you for the type of site you want to create, as in Figure 2-7.

image from book
Figure 2-7: The options available for creating a new Web site with Visual Studio .NET 2005.

If you select the Web Site option, Visual Studio generates the minimum number of files for a Web site to build. Basically, it creates a default .aspx page and an empty Data directory. If you opt for a personal Web site, an ASP.NET starter kit is used to give you a functional Web site with several standard features built in. Let's go for a Web site. Visual Studio .NET 2005 creates a project file but doesn't use it to track all the files that form an application. The root directory of the site implicitly defines a Web project. Any file or folder added or created under the root is automatically part of the project.

Page Design Features

The ASP.NET front-end of an application can include several types of entities, the most important of which are pages. To edit a Web page, you can choose between two views Design and Source. The Design view displays the HTML layout, lets you select and edit controls and static elements, and provides a graphical preview of the page. The Source view shows the HTML markup along with the inline code. The markup is syntax-colored and enriched by features such as IntelliSense, tips, and autocompletion.

You choose the template of the item to add to the site from the menu shown in Figure 2-8.

image from book
Figure 2-8: Item templates supported by Visual Studio .NET 2005.

Note the two check boxes that appear at the bottom of the window. You can choose to keep the code of the page in a separate file (similar to the code-behind model of Visual Studio .NET 2003) and can associate the current page with a master page. Master pages are a cool new feature of ASP.NET 2.0 that we'll discuss thoroughly in Chapter 6. The code-behind schema touted by Visual Studio .NET 2003 has been revised and restructured. As a result, pages built with Visual Studio .NET 2005 are not forced to use code separation (that is, the page is separated into .aspx and .cs files). Code separation is still fully supported and recommended, but it is now optional.

Before we get to add some code to build a sample page, let's review some design-time features of the page.

Master Pages

The master page is a single file that defines the template for a set of pages. Similar to an ordinary .aspx page, the master contains replaceable sections that are each marked with a unique ID. Pages in an application that will inherit the structure defined in the master reference the master page in their @Page directive or even programmatically. A page based on a master is said to be a content page. One master page can be bound to any number of content pages. Master pages are completely transparent to end users. When working with an application, a user sees and invokes only the URL of content pages. If a content page is requested, the ASP.NET runtime applies a different compilation algorithm and builds the dynamic class as the merge of the master and the content page.

Master pages are among the hottest new features of ASP.NET 2.0 and address one of the hottest threads in many ASP.NET 1.x newsgroups. By using master pages, a developer can create a Web site in which various physical pages share a common layout. You code the shared user interface and functionality in the master page and make the master contain named placeholders for content that the derived page will provide. The key advantage is that shared information is stored in a single place the master page instead of being replicated in each page. Second, the contract between the master and content page is fixed and determined by the ASP.NET Framework. No change in the application or constituent controls can ever break the link established between master and content.

Important 

ASP.NET 2.0 master pages offer one way of building Web pages. In no way are master pages the only or preferred way of building Web sites. You should use master pages only if you need to duplicate portions of your user interface or if your application lends itself to being (re)designed in terms of master and content pages.

Content Pages

The master defines the common parts of a certain group of pages and leaves placeholders for customizable regions. Each content page, in turn, defines what the content of each region has to be for a particular .aspx page. A content page is a special type of ASP.NET page, as it is allowed to contain only <asp:Content> tags. Any classic HTML tags including client-side <script> and comments are not allowed and if used raise compile errors.

The reason for this lies in the implementation of the master page feature. Because the content regions are substituted into the master page placeholders, the destination for any literal markup (that is, comments, script, other tags) would be ambiguous, because the same kind of content is also allowed in the master.

Visual Studio .NET offers a special Design view of content pages, as Figure 2-9 demonstrates. The view contains as many drawing surfaces as there are content regions in the master. At the same time, the master layout is displayed in the background grayed out to indicate that it's there but you can't access it.

image from book
Figure 2-9: Content pages in Visual Studio .NET 2005.

Important 

Content pages can be used only in conjunction with master pages. A Web Forms page silently becomes a content page when you check the Select Master Page option in the dialog box shown in Figure 2-8.

Code-Behind Classes

When you add new Web Forms and require code and layout separation, a C# (or Visual Basic .NET) class file is created along with the .aspx file in the same folder. The class file is named after the .aspx resource simply by adding a language extension. For example, if the Web Forms is named WebForm1.aspx, the corresponding code-behind class is named WebForm1.aspx.cs. This name is just the default name, and it obeys the default naming convention. Although it is not recommended for the sake of consistency, you should feel free to rename the class file to whatever name you like.

Nothing bad can happen to your application if you make it use inline code instead of code and layout separation. Nonetheless, real-world pages need a good amount of server code, and appending all that code to the <script> tag of the .aspx file makes the file significantly hard to read, edit, and maintain. Code-behind, on the other hand, is based on the idea that each Web Forms page is bound to a separate class file that contains any code that is relevant to the page. The code-behind class ends up being the basis of the dynamically generated page class that the ASP.NET runtime creates for each requested .aspx resource. All the server code you need to associate to the .aspx resource flows into the code-behind class. The code-behind model promotes object-orientation, leads to modular code, and supports code and layout separation, allowing developers and designers to work concurrently to some extent.

Visual Studio .NET 2005 delivers an improved page model even though the overall syntax is nearly identical to that of previous versions. There are two main changes you'll notice in Visual Studio .NET 2005. First, having the code in a separate class file is now optional. (See Figure 2-8.) Second, thanks to partial classes a .NET Framework-specific feature available only in version 2.0 multiple developers (and designers) can work on the same page at the same time. A partial class is a .NET class defined across multiple source files that the compiler sews back together.

Note 

You should use code-behind classes for all your project pages, except test pages you quickly arrange in the context of toy applications or to verify a given feature. Using the code-behind model along with the principle of class inheritance gives you enough programming power to create a hierarchy of classes to cut off development time and maximize code reusability.

The Toolbox of Controls

A Web Forms page is mostly made of controls either predefined HTML and Web controls, user controls, or custom controls. Except for user controls (.ascx files), all the others are conveniently listed in the editor's toolbox. (See Figure 2-10.) The toolbox can be toggled on and off and is an easy way to pick up the control of choice and drop it onto the Web form via a drag-and-drop operation. The toolbox is visible only if .aspx resources are selected, either in Design or Source view.

image from book
Figure 2-10: The Visual Studio .NET 2005 toolbox.

The toolbox is widely customizable and supports the addition of new controls as well as the creation of new user-defined tabs. Controls defined in a project within the current solution are automatically added to the toolbox.

Editor's Special Capabilities

The Visual Studio .NET 2005 code editor presents some interesting features that prove the team commitment to excellence and all users' satisfaction. I'd like to call your attention to four of them: check for accessibility, markup preservation, simplified tabification and indentation, and target schema validation.

A button on the HTML source editing toolbar allows you to select a few accessibility requirements and validate the page's code against them. (See Figure 2-11.)

Note how many recommendations you get even for an empty page. Among other things, you're invited to synchronize alternatives and captions with time-based multimedia tracks, and to ensure that you don't convey information using color alone.


Figure 2-11: The dialog box that allows you to select options for an accessibility check.

Visual Studio .NET 2005 preserves the formatting of your HTML edits and doesn't even attempt to reformat the source as you switch between views. At the same time, it comes with powerful features for indentation and tag formatting that you can optionally turn on. The days of the Visual Studio .NET 2003 autoformatting features kicking in on view switching are definitely gone.

In Figure 2-12, you see the list of supported client targets. Once you select a target, the whole editing process is adapted to the features of the specified device. Want a quick example? Imagine you select Netscape Navigator 4.0 (NN4) as the client target. NN4 doesn't recognize the <iframe> tag; instead, it sports the <layer> tag with nearly the same characteristics. As Figure 2-13 shows, Visual Studio .NET detects the difference and handles it correctly. IntelliSense doesn't list iframe but prompts you for layer. If you insist and type in <iframe> anyway, a squiggle shows up to catch your attention.

image from book
Figure 2-12: The list of client targets for which Visual Studio .NET can cross-check your markup.


Figure 2-13: The code editor is sensitive to the selected client target schema.

Note 

The number of ASP.NET client targets is significantly larger in Visual Studio .NET 2005 and ranges from Internet Explorer 6.0 to HTML 3.2 (covering Internet Explorer 3.x and Netscape Navigator 3.x). Other validation targets are mobile schemas (Compact HTML 1.0 and mobile HTML 3.2), Netscape 4.0, and the XHTML 1.0 Transitional schema. The latter schema covers browsers such as Netscape 7.0 and Opera 7.0.

Code Refactoring

When a .vb or a .cs file is open for editing in Visual Studio .NET 2005, a new menu appears on the top-most menu strip the Refactor menu, shown in Figure 2-14.

image from book
Figure 2-14: The new menu for helping developers to quickly refactor the code of classes.

As you can see, the menu provides advanced facilities for code editing. Among the other things, you can extract a block of code and transform it into a new method or rename a member all the way through. The refactor feature doesn't disappoint when it comes to managing properties. Admittedly, one of most boring tasks when writing classes is turning a field into a property with get and set accessors. Imagine you have a field like the following one:

private int _counters; 

At a certain point, you might realize that a full-featured property would be better. Instead of typing code yourself, you just select the line and refactor to encapsulate the field. Needless to say, the menu item is Refactor|Encapsulate field. With the power of a click, the old code becomes the following:

public int Counters {     get     {         return _counters;     }     set     {         _counters = value;     } } 

You are free to change the public name of the property and, of course, to flesh out the bodies of the get/set accessors.

Import/Export of IDE Features

It is common for developers to move a project from one machine to another. This happens for a variety of reasons. For example, you might use multiple machines for test purposes; you continually swing between the client's site and your own office; you are an absolute workaholic who just can't spend a night home without working.

Typically, the various machines have Visual Studio .NET installed with the same set of features, and although it's not necessary, they share the same set of IDE settings. To feel comfortable with the environment, you might have developed macros, reordered menus and toolbars, added new controls to the toolbox, created new project templates, and assigned preferences for colors and fonts. This wealth of information is not easy to catalog, organize, and persist if you have to do that manually.

Figure 2-15 shows the new Import/Export Settings dialog box associated with the Tools menu. You select the IDE settings you want to persist and save them to a file. The file can be created anywhere and is given a .vssettings extension. In spite of the extension, it is an XML file.

image from book
Figure 2-15: The wizard for importing and exporting IDE settings.

Adding Code to the Project

Adding code to the project mostly means that you added Web Forms to the project and now need to hook up some of the page events or events that controls in the form generate. In addition, you might want to add some classes to the project representing tailor-made functionalities not otherwise available.

Filling a Web Forms page is easy and intuitive. You open the form in layout mode and drag and drop controls from the toolbox onto it. Next, you move elements around and configure their properties. If needed, you can switch to the Source view and manually type the HTML markup the way you want it to be.

A pleasant surprise for many developers is that you can drag and drop controls from the toolbox directly into the Source view; instead of viewing the control graphically rendered, you see the corresponding markup code. Similarly, you can edit the properties of a server control by selecting it in the Design view or highlighting the related HTML in the Source view. In addition, each control deployed on the form can have its own design-time user interface through which you can configure properties for the run time.

Defining Event Handlers

Adding code to a Web Form page means handling some page's or control's events. How do you write an event handler for a particular page element? To try it out, place a button on a form and double-click. Visual Studio switches to the Source view and creates an empty event handler for the control's default event. For a button control, it is the Click event. The code you get looks similar to the following:

void Button1_Click(object sender, EventArgs e) {     ... } 

The HTML markup is automatically modified to contain an additional OnClick attribute:

<asp:button runat="server"      text="Click"     OnClick="Button1_Click" /> 

Notice that event binding is always done declaratively in the body of the .aspx page. Unlike its predecessor, Visual Studio .NET 2005 doesn't inject automatically generated code in the page for event wireup. Recall that in Visual Studio .NET 2003, double-clicking a button adds the following (C#) code to the code-behind class:

// VS.NET injects this code in the code-behind class of a page // when you double-click a button to handle its default event Button1.Click += new EventHandler(this.Button1_Click); 

The code would obviously be different if Visual Basic .NET is your language of choice.

If you're dealing with a code-behind page, the event handler is defined in the code-behind class instead of being placed inline.

When you double-click on a control or on the body of the page, a handler for the default page or control event is generated. What if you need to write a handler for another event? You select the desired control and click on the Events icon in the Properties window. You get a view like that in Figure 2-16 and pick up the event you need.


Figure 2-16: The Events view in the Properties window.

Writing Helper Classes

Writing helper classes is as easy as adding a new class to the project, as shown in Figure 2-17.

image from book
Figure 2-17: Adding a new class to an ASP.NET project.

The class file can define any number of classes, even partial class definitions, and will actually be compiled to an assembly. Where should you deploy this class file in your project? You have two options: either you create an additional project to generate a DLL component library or you drop the class file in a special folder below the application's virtual root the App_Code folder.

In the former case, you add another project to the solution by using the File|Add menu. From the list of available projects, you pick up a Class Library project and then add any class files to it. When you're done, you reference the library project in the Web site project and go. Pleasantly enough, IntelliSense will just detect new classes and work as expected.

What's the App_Code folder, then? It is an application's subdirectory that has a special meaning to the ASP.NET runtime. The App_Code folder is designed to contain reusable components that are automatically compiled and linked to the page code. The folder stores source class files (.vb or .cs) that the ASP.NET runtime engine dynamically compiles to an assembly upon execution. Created in a predefined path visible to all pages in the site, the resulting assembly is updated whenever any of the source files are updated. It is important to note that any file copied to the App_Code folder is deployed as source code on the production box. (I'll say more about special ASP.NET directories in the next section.)

Building a Sample Shared Class

To experience the advantages of reusable source components, let's design a page that makes use of a nontrivial component that would be annoying to insert inline in each page that needs it. The page looks like the one in Figure 2-18.

image from book
Figure 2-18: The PswdGen.aspx page to generate a new "strong" password of the specified length.

Many products and services available over the Web require a strong password. The definition of a "strong password" is specific to the service, but normally it addresses a password at least eight characters long with at least one character from each of the following groups: uppercase, lowercase, digits, and special characters. We'll use that definition here. The sample page you will build asks the user for the desired length of the password and suggests one built according to the rules just mentioned. You create a new file named StrongPassword.cs and place it in the purposedly created App_Code subdirectory. The class outline is shown here:

public class StrongPassword {     public StrongPassword()     {...}     public string Generate()     {...}     public string Generate(int passwordLength)     {...} } 

The class features one method Generate that will actually generate a new strong password. Of course, the definition of a "strong password" is arbitrary. Once placed in the App_Code directory, this class is compiled on demand and made available to all pages. In the sample page, the code to generate and validate a password becomes simpler and more readable:

void buttonGenerate_Click(Object sender, System.EventArgs e) {     // Gets the desired length of the password and ensures     // it is really expressed as a number. (This is a simple but     // effective pattern to prevent code/data injection.)     int pswdLen = 8;     bool result = Int32.TryParse(PswdLength.Text, out pswdLen);     // Create and display the new password     StrongPassword pswd = new StrongPassword();     labelPassword.Text = pswd.Generate(pswdLen); } 

Figure 2-18 shows the page in action. Note that the same functionality can also be achieved by placing the code inline or packing the StrongPassword class in a separate assembly.

A Look at the web.config File

The behavior of an ASP.NET application is affected by the settings defined in various configuration files machine.config and web.config. The machine.config file contains default and machine-specific values for all supported settings. Machine settings are normally controlled by the system administrator, and applications should never be given write access to it. An application can override most default values stored in the machine.config file by creating one or more web.config files.

At a minimum, an application creates a web.config file in its root folder. The web.config file is a subset of machine.config, written according to the same XML schema. Although web.config allows you to override some of the default settings, you cannot override all settings defined in machine.config.

If the application contains child directories, it can define a web.config file for each folder. The scope of each configuration file is determined in a hierarchical, top-down manner. The settings actually applied to a page are determined by the sum of the changes that the various web.config files on the way from machine.config to the page's directory carry. Any web.config file can locally extend, restrict, and override any type of settings defined at an upper level. If no configuration file exists in an application folder, the settings valid at the upper level are applied.

Visual Studio .NET usually generates a default web.config file for you. The web.config file is not strictly necessary for an application to run. Without a web.config file, though, you can't debug the application.

ASP.NET Reserved Folders

ASP.NET uses a number of special directories below the application root to maintain application content and data. In ASP.NET 1.x, only the Bin directory was used. ASP.NET 2.0 introduces seven additional protected directories. None of these directories are automatically created by ASP.NET 2.0 or Visual Studio .NET 2005, nor are the directories necessarily required to exist. Each directory needs to be created either manually by developers or on demand through Visual Studio .NET when a feature that requires it is enabled.

Additional Application Directories

Table 2-1 lists all the additional directories you can take advantage of. Note that the directories will be there only if they are required by your specific application. Don't be too worried about the number of new directories (that is, seven) you can potentially have. A reasonable estimate would be that only two or three (out of seven) additional directories will be present in an average ASP.NET application.

Table 2-1: Special Reserved Directories in ASP.NET Applications

Directory Name

Intended Goal

Bin

Contains all precompiled assemblies needed by the application.

App_Browsers

Contains browser capabilities information.

App_Code

Contains source class files (.vb or .cs) used by pages. All the files must be in the same language; you can't have both C# and VB.NET files in the folder.

App_Data

Contains data files for the application. This can include XML files and Access databases to store personalization data.

App_GlobalResources

Contains .resx resource files global to the application.

App_LocalResources

Contains all .resx resource files that are specific to a particular page.

App_Themes

Contains the definition of the themes supported by the application. (I'll say more about themes in Chapter 6.)

App_WebReferences

Contains .wsdl files linking Web services to the application.

The content in all the directories listed in Table 2-1 won't be accessible via HTTP requests to the server. The only exception is the content of the App_Themes folder.

Important 

The names of these folders aren't customizable. The reason lies in the way the ISAPI filter in charge of blocking HTTP requests to these folders work. For performance reasons, the ISAPI filter can't just access the web.config file to read about directory names to look for. That would require the filter to parse the XML file on any request and, as you can easily imagine, would be a major performance hit. Alternately, the names of the directories could have been written in the registry, which would make for a much faster and affordable access. Unfortunately, a registry-based approach would break XCopy deployment and introduce a major breaking change in the ASP.NET architecture. (See the "Application Deployment" section for more information on XCopy deployment.)

The contents of many folders listed in Table 2-1 are compiled to a dynamic assembly when the request is processed for the first time. This is the case for themes, code, resources, and Web references. (See the "Resources" section for more information on the ASP.NET 2.0 compilation model.)

The App_Code Directory

As mentioned, you can use the server App_Code directory to group your helper and business classes. You deploy them as source files, and the ASP.NET runtime ensures that classes will be automatically compiled on demand. Furthermore, any changes to these files will be detected, causing the involved classes to recompile. The resulting assembly is automatically referenced in the application and shared between all pages participating in the site.

You should put only components into the App_Code directory. Do not put pages, Web user controls, or other noncode files containing noncode elements into the subdirectory. The resulting assembly has application scope and is created in the Temporary ASP.NET Files folder well outside the Web application space.

Note 

If you're worried about deploying valuable C# or VB.NET source files to the Web server, bear in mind that any (repeat, any) access to the App_Code folder conducted via HTTP is monitored and blocked by the aforementioned ASP.NET ISAPI filter.

Note that all class files in the App_Code folder must be written in the same language be it Visual Basic .NET or C# because they are all compiled to a single assembly and processed by a single compiler. To use different languages, you must organize your class files in folders and add some entries to the configuration file to tell build system to create distinct assemblies one per language.

Here's an example. Suppose you have two files named source.cs and source.vb. Because they're written in different languages, they can't stay together in the App_Code folder. You can then create two subfolders say, App_Code/VB and App_Code/CS and move the files to the subfolder that matches the language. Next you can add the following entries to the web.config file:

<configuration> <system.web> <compilation>     <codeSubDirectories>         <add directoryName="VB" />         <add directoryName="CS" />     </codeSubDirectories> </compilation> </system.web> </configuration> 

Note that the <codeSubDirectories> section is valid only if it is set in the web.config file in the application root. Each section instructs the build system to create a distinct assembly. This means that all the files in the specified directory must be written in the same language, but different directories can target different languages.

Note 

The App_Code directory can also contain XSD files, like those generated for typed DataSets. An XSD file represents the strongly typed schema of a table of data. In the .NET Framework 1.1, a typed DataSet must be manually created using the xsd.exe tool. In ASP.NET 2.0, all you have to do is drop the source XSD file in the App_Code folder.

The Resource Directories

A localizable Web page uses resources instead of hard-coded text to flesh out the user interface of contained controls. Once a resource assembly is linked to the application, ASP.NET can select the correct property at run time according to the user's language and culture. In ASP.NET 1.x, developers had to create satellite assemblies manually. ASP.NET 2.0, on the other hand, creates resource assemblies parsing and compiling any resource files found in the two supported folders App_LocalResources and App_GlobalResources.

A local resource is a resource file specific to a page. A simple naming convention binds the file to the page. If the page is named sample.aspx, its corresponding resource file is sample.aspx.resx. To be precise, this resource file is language neutral and has no culture defined. To create a resource assembly for a specific culture, say Italian, you need to name the resource file as follows: sample.aspx.it.resx. Generally, the it string should be replaced with any other equivalent string that identifies a culture, such as fr for French or en for English. Figure 2-19 shows the a sample local resource folder.


Figure 2-19: The local resource directory for the respage.aspx page.

Local resources provide a sort of implicit localization where the page itself automatically ensures that each contained control is mapped to a particular entry in the .resx file. Here's how a simple page changes once you add support for local resources.

<%@ Page Language="C#" meta:resourcekey="PageResource1" UICulture="auto" %> <html> <head  runat="server">     <title>Pro ASP.NET (Ch 02)</title> </head> <body> <h1>    <asp:Label runat="server"  meta:resourcekey="LabelResource1" /> </h1> <form  runat="server">     <asp:Button  Runat="server" meta:resourcekey="BtnResource1" /> </form> </body> </html> 

The page itself and each constituent control are given a resource key. The .resx file contains entries in the form ResourceKey.PropertyName. For example, the Text property of the button is implicitly bound to the BtnResource1.Text entry in the .resx file. You don't have to write a single line of code for this mapping to take place. You are only requested to populate the resource files as outlined. The UICulture attribute set to auto tells the ASP.NET runtime to use the current browser's language setting to select the right set of resources.

Tip 

To quickly test a page against different languages, you open the Internet Explorer Tools menu and click the Languages button. Next, you add the language of choice to the list box of supported languages and move the language of choice to the first position in the list. Click OK and exit. From now on, Internet Explorer will be sending the selected language ID with each served request.

Figure 2-20 shows how the same page looks when different languages are set.

image from book
Figure 2-20: The respage.aspx file in English and Italian.

Implicit localization works automatically, meaning that you don't need to specify how to read information about each property from a resource file. However, at times you need more direct control over how properties are set. For this, you turn to global resources. When you choose to add a resource file to the application, Visual Studio .NET creates the App_GlobalResources directory and places a new .resx file in it. You can rename this file at will and fill it with strings, images, sounds, and whatever else is suitable to you. (See Figure 2-21.)

image from book
Figure 2-21: The Visual Studio .NET Resource editor in action.

Within the page or controls code, you reference resources using an expression, as in the following code:

<asp:Label Runat="server" Text="<%$ Resources:Resource, Msg1 %>" /> 

Resources is the namespace of the object, whereas Resource is the name of the .resx file that contains the resources. Finally, Msg1 is the name of the entry to use. Explicit localization is useful when you have large bodies of text or custom messages you want to localize.

Note 

The resulting resource assembly for the neutral culture has application scope and is therefore referenced from other assemblies generated in the application. All types defined in the resource assemblies belong to the Resources namespace and are static objects.

Linked Web Services

When you add a reference to a Web service, the .wsdl file for the Web service is downloaded and copied to the App_WebReferences directory. At runtime, any WSDL file found in the Web reference directory is dynamically compiled in a C# or Visual Basic .NET proxy class in much the same way as business classes in the App_Code directory are processed.

Note that in ASP.NET 1.x, you have to reference the Web service and have Visual Studio .NET 2003 to generate the proxy class explicitly. If you can obtain a WSDL file in other ways (that is, you don't download it through the Add Web Reference Wizard), you can add it manually to the App_WebReferences directory.

Available Themes

The App_Themes directory defines one or more themes for controls. A theme is a set of skins and associated files such as style sheets and images that can be used within an application to give a consistent user interface to controls. In the App_Themes directory, each theme occupies a single subdirectory, which has the same name as the theme. All related files are stored in this directory.

When a theme is loaded, the contents of the theme directory are parsed and compiled into a class that inherits from a common base class. Any theme defined outside the App_Themes directory is ignored by the ASP.NET build system.

Build the ASP.NET Project

To build and run the ASP.NET application, you simply click the Start button on the toolbar (or press F5) and wait for a browser window to pop up. In Visual Studio .NET 2005, no compile step takes place to incorporate code-behind and helper classes. All the dynamically generated assemblies, and all precompiled assemblies deployed into the Bin folder, are linked to the application as used to visit pages.

Once any needed assemblies have been successfully built, Visual Studio .NET autoattaches to the ASP.NET run-time process typically, w3wp.exe for debugging purposes. Next, it opens the start page of the application.

Important 

The ASP.NET run-time process might differ based on the process model in use. The process model is configurable; the default model, though, depends on the underlying operating systems and Web server settings. If your Web server runs Windows 2000 Server, or perhaps any version of Windows XP, the run-time process is aspnet_wp.exe. It runs under a weak user account named ASPNET and is designed to interact with IIS 5.x. If you run Windows 2003 Server and IIS 6.0 and didn't change the default process model, the run-time process is w3wp.exe, which is the standard worker process of IIS 6.0. The w3wp.exe process runs under the NETWORK SERVICE account. This process doesn't know anything about ASP.NET, but its behavior is aptly customized by a version-specific copy of the ASP.NET ISAPI extension. Under IIS 6.0, you can even switch back to the IIS 5 process model. If you do so, though, you lose a lot in performance.

When you build the project, Visual Studio .NET 2005 might complain about a missing web.config file, which is necessary if you want to debug the code. If you just want to run the page without debugging it, click the Run button in the message box you get. Otherwise, you let Visual Studio generate a proper web.config file for you. If you create your own web.config file, make sure it contains the following string to enable debugging:

<compilation debug="true" /> 

Once this is done, you can commence your debugging session.

Debugging Features

As long as you compiled the project in debug mode (which is the default indeed), you can set a few breakpoints in the sources and step into the code, as shown in Figure 2-22.

image from book
Figure 2-22: Stepping into the code of the page by using the Visual Studio .NET integrated debugger.

The Debug menu is a little richer in Visual Studio .NET 2005 than it was in the previous version. You now have more choices as far as exceptions and breakpoints are concerned. In particular, you can configure the IDE so that it automatically breaks when an exception is thrown. The feature can be fine-tuned to let you focus on any exceptions, any exceptions in a specified set, or all exceptions not handled by the current application.

Breakpoints can be set at an absolute particular location or in a more relative way when the execution reaches a given function. Braveheart debuggers also have the chance to break the code when the memory at a specified address changes.

Watch windows feature a richer user interface centered around the concept of visualizers. A visualizer is a popup window designed to present certain types of data in a more friendly and readable manner XML, text, or DataSets. (See Figure 2-23.)

image from book
Figure 2-23: The text visualizer invoked from the quick-watch window during a debug session.

Visualizers are also active from within code tip windows. A code tip is the made-to-measure ToolTip that previews the value of variables during a debug session. (See Figure 2-24.)

Visualizers are defined for a few types of data. Personally, I just love the DataSet visualizer. Checking what's in a DataSet instance couldn't be easier.

image from book
Figure 2-24: Invoking a visualizer from within a code tip.

Testing the Application

As mentioned, there are two ways of testing pages in Visual Studio .NET 2005. You can have pages served by IIS (if installed) or by the embedded local Web server. By default, Visual Studio .NET uses IIS if you open the project as a Web site and indicate its URL; otherwise, it defaults to the local Web server. An important point to consider about the embedded Web server concerns the security context. Under IIS, an ASP.NET application is served by a worker process running under the real account defined for the application typically, a highly restricted account such as ASP.NET or NETWORK SERVICE.

In contrast, the embedded Web server takes the security token of the currently logged-on user that is, you. This means that if the developer is currently logged on as an administrator a much more common scenario than it should be the application receives administrative privileges. The problem here is not a risk of being attacked; the real problem is that you are actually testing the application in a scenario significantly different from the real one. Things that work great under the local Web server might fail miserably under IIS.

For simple applications that only read and run ASP.NET pages, this problem is not that relevant. However, the results of your testing under the local server will become less reliable if you access files other than Web pages, files located on other machines, files in the Windows registry, or files on a local or remote database. In all these cases, you must make sure that the real ASP.NET account has sufficient permissions to work with those resources.

The bottom line is that even though you can use the local Web server to test pages, it sometimes doesn't offer a realistic test scenario.

 


Programming Microsoft ASP. Net 2.0 Core Reference
Programming Microsoft ASP.NET 2.0 Core Reference
ISBN: 0735621764
EAN: 2147483647
Year: 2004
Pages: 112
Authors: Dino Esposito
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net