Creating Web Sites with ASP



Creating Web Sites with 2.0

From basic, static HTML pages to totally data-driven and data-centric Web applications, the demands on a Web developer are much more complex and demanding than they were just a few years ago. The advent of social networking sites like dotnetspider, which is written in 2.0; interactive mapping sites; and sites streaming full-motion video has required developers to adapt and change. One of the best tools to use to build these types of web applications is Microsoft's 2.0. This article delves into some of the more interesting features of 2.0 and shows you how to begin using 2.0 on your next web project.

• A wide variety of web controls

• Project folders to help organize files

• Master pages and themes

• Site navigation features

• Enhanced data access features

• Membership and personalization

In this article I'll take a detailed look at a number of these features including Visual Studio 2005 enhancements, the code-behind model, the web controls, the master pages feature, the themes and skins feature .

Creating a Web Site

With the release of Visual Studio 2005 SP1, Microsoft offers web site developers a choice between two different project types: the Web Site and the Web Application. The Web Site project really is not a project at all since Visual Studio 2005 solution and project files are not created. In the Web Site model all pages and code are stored in a directory, much like the traditional ASP model. When it comes to deployment, the easiest approach is to copy all of your files to your web server and everything compiles on demand. You could also use the aspnet_compiler.exe utility to precompile your site into a binary file and deploy to your web site.

The Web Application project is an implementation of the type of web project available in Visual Studio 2003 and consists of a solution (.sln) and project files (.vbproj). It is the result of Microsoft listening to the 2.0 developer community and responding to the needs of the community. It provides the benefit of generating a single assembly in the local /bin folder ready for deployment. This model also makes it easier to incrementally deploy changes made to your site. If you are converting a web application from Visual Studio 2003, this is the project model you are going to want to adopt. I use this model with most of the web applications I develop.

To create a web site with the Web Application project model, launch Visual Studio 2005 and from the File menu option choose New Project… and the New Project dialog box will appear (see Figure 1). Choose Web Application, the name of the project, the location, and the name of the solution if you select to have one created or specify if you want the new project added to the current solution. Click OK and Visual Studio will create the .sln and the .vbproj files (because it's a Visual Basic project), a default.aspx page, and a web.config file.

|[pic] |[pic] | |

|  |  | |

| | | |

|Figure 1: The New Project dialog box specifies the name, |Figure 2: The New Web Site dialog box specifies the name, | |

|location, and language for your web application. |location, and language for your web site. | |

| | | |

| | | |

To create a web site with the Web Site project model, launch Visual Studio 2005 and from the File menu option choose New Web Site and the New Web Site dialog box will appear (see Figure 2). Choose Web Site, the location of the web site, the language used, and lastly, the name of the web site.

I don't need to explain the name of the web site and the language you want to use, but I'll discuss other options. The location dropdown offers three options: File System, HTTP, and FTP. Creating a File System Web site is the simplest approach because your web site can reside in any directory on your hard drive or shared network drive. The advantage of a File System web site is that you can run it using Visual Studio 2005's built-in development web server. You don't need IIS (although you can use IIS to run a File System web site by creating a virtual directory for the directory in which you are storing the web site).

|[pic] |  |

|Figure 3: The web site location can be | |

|an FTP folder on a distant server. | |

Choosing HTTP as the location will direct Visual Studio 2005 to automatically create a web site in an IIS virtual directory. This saves you the step of creating the virtual directory in IIS, but obviously you need to have access to an IIS server.

Choosing FTP as the location allows you to actually store and even code your application on a remote web server somewhere. If you've selected this option, click the Browse button to display the Choose Location dialog box and then select a directory, an IIS virtual directory, and then enter the parameters required to log on to an FTP location (see Figure 3).

After you have decided on the name, location, and language for your new web site, click the OK button to create the site. Visual Studio will create a Default.aspx page, web.config file, and an App_Data folder. One primary difference between the Web Site project model and the Web Application project model is that in the Web Site model settings are stored in a web.config file as opposed to a project file.

System-Defined Folders

Table 1 illustrates some special system-defined folders.

Table 1. System-Defined Folders: uses these system-defined folders to hold specific portions of applications.

|Folder Name |Description |

|App_Code |Reusable, non-page classes that are dynamically compiled at run time and made available to the |

| |application as a single assembly. Examples include utility classes and business objects. |

|App_Data |Designed to contain file-based databases used by the application including SQL Server Express |

| |(.mdf) and Access (.mdb) databases. |

|App_WebReferences |Stores Web service references used by the application. |

|App_Browsers |Stores browser definition files used by to identify individual browsers and determine |

| |their capabilities. |

|App_Themes |Stores all of the specific themes and skins for the application. |

You store all of your non-page classes such as utility classes, business objects, or any other classes you may have created in the App_Code folder. To add an App_Code folder to your project, right-click the project name and select "Add Folder" and then select App_Code. monitors the folder, so whenever you change a class in the App_Code folder, will dynamically recompile the class and automatically make it available to the entire site. You can even place classes coded in different languages in subdirectories under the App_Code directory. Each subdirectory needs to be registered with a particular language in web.config.

The App_Data folder makes database integration easy. The App_Data folder holds file-based data stores including SQL Server Express 2005 database files (.mdf files), Access database files (.mdb files), Excel worksheets, XML files, and so on. The primary advantage of using App_Data is that files placed there are not downloadable if a request is made for the file over the wire.

|[pic] |  |

|Figure 6: You can elect to set the current page or a specific page as the start page in the Start Options in the project's Properties dialog. | |

's compilation model offers a number of benefits including the ability to run the current form each time you run the site. A project's Start Options, available on the project's Property Pages dialog box, specifies, among other options, the ability to launch the current page or a specific page each time the site is launched (see Figure 6). See the article by Rick Strahl referred to in the "Reading Suggestions" sidebar.

The Web Site Administration Tool page (see Figure 7) makes it fairly easy to administer your web site. You can launch it by selecting the Administration icon on the top of the Solution Explorer (see Figure 8). You can manage all aspects of your site with this tool including security, application settings, and providers. The security features include being able to add and delete users, assign folder permissions, add and delete user roles, and assign users to specific roles. The application settings include being able to add and remove application variables, configure email settings, take the site offline, configure the debugging and tracing options, and specify which page to use as the default error page.

|[pic] |[pic] |

|  | |

| | |

|Figure 7: The Web Site Administration Tool | |

|provides site configuration features. | |

| | |

| | |

2.0 Web Controls

I'd like to now spend a little time discussing some of the important web controls in 2.0, including the BulletedList, HiddenField, Multiview, Wizard, and ImageMap controls.

BulletedList Control

The BulletedList control provides a quick and easy way to develop both bulleted and numbered lists. You can manually enter a list (see Figure 9) or you can use data binding to populate the items in the list. The BulletStyle property offers a number of options for bulleted and numbered lists.

HiddenField Control

Storing data in hidden fields on a page is nothing new—and is in fact a very common technique to save state data across posts back to the server. 2.0's HiddenField control provides the ability to create a hidden field on a page and use it to store data to be sent back to the server on a post back.

FileUpload Control

Many web sites provide the ability for users to upload files. For example, an employment recruiting firm may allow people to upload their resume, or a printing company might allow customers to upload their print jobs. Microsoft's team designed the FileUpload control to make this an easy feature to add to your site. The FileUpload control is comprised of a textbox to allow the user to type the file information and a Browse button that allows the user to go search for the file. To get the file uploaded you must add a separate button that results in a postback and executes the code to upload the file:

Protected Sub Button1_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Button1.Click

Dim FilePath As String = _

Request.PhysicalApplicationPath & "Uploads\"

If (FileUpload1.HasFile) Then

Dim FileName As String = Me.FileUpload1.FileName

FilePath += FileName

Me.FileUpload1.SaveAs(FilePath)

Label1.Text = "Your file was saved as " & _

strFileName

Else

Label1.Text = "Please select a file to upload."

End If

End Sub

|In the preceding code, the FilePath variable will hold the folder location to which the file will be | |

|uploaded. If there is a value in the textbox portion of the FileUpload control, indicated by the HasFile| |

|property, then the file name is combined with the file upload path. Next, the SaveAs method for the | |

|control is executed thereby actually uploading the file. | |

| | |

|Figure 12: Use the Wizard control to implement step-by-step processes. | |

Wizard Control

The Wizard control works much like the MultiView control in that they both contain sections to place controls in. While the sections in a MultiView control are views, the sections in a Wizard control are called steps. These steps are stored in the WizardSteps collection. The primary difference between the two controls is that the Wizard control can display links to all of the steps in a sidebar on the left-hand side of the control (see Figure 12). The DisplaySideBar property controls the display of the sidebar.

You can add or remove steps from a wizard control by selecting the Add/Remove WizardSteps option from the smart tag Wizard Tasks menu.

Each step is configured to be of a certain type. The StepType attribute determines how the step behaves and which buttons appear on the step (see Table 2).

Table 2. StepType Attribute Settings: The StepType attribute accepts these values.

|Attribute |Description |

|Auto |This is the default setting. It automatically sets the first step as a Start step, the last as a Finish step, and |

| |all others as Step steps. |

|Complete |Specifies that the step has no sidebar or navigation buttons. Displaying a completion message is a common usage for |

| |this type of step. |

|Finish |Specifies that the step has a Previous button and a Finish button. |

|Start |Specifies that the step does not have a Previous button and does have a Next button. |

|Step |Specifies that the step has a Previous button and a Next button. |

Based on the value of a step's StepType property, the built-in Next, Previous, Finish, and Cancel buttons control all the page-by-page navigation tasks automatically. Setting the DisplayCancelButton property to True causes the Cancel button to be displayed. Clicking the Cancel button causes the CancelButtonClick event to fire. You can set the value in the ActiveStepIndex property to manually select the active step. You can code event handlers for a number of Wizard events such as ActiveStepChanged, NextButtonClick, PreviousButtonClick, and SidebarButtonClick.

ImageMap Control

HTML has supported image maps for what seems like hundreds of years, and 2.0 supports them in the form of the ImageMap control. Just in case you're unaware of what an image map is and how it works, image maps contain clickable regions called hotspots. A developer can configure each hotspot to respond when clicked on by a user. 2.0's ImageMap control supports three different types of hotspot objects: CircleHotSpot, RectangleHotSpot, and PolygonHotSpot. Unfortunately Visual Studio 2005 does not provide an editor to easily define hotspot x and y coordinates, so you need to use an external graphics program.

You use the ImageURL property to determine the image to display in the control. You add hotspots by clicking the ellipses button for the HotSpots collection and launching the HotSpot Collection Editor (see Figure 13).

|[pic] |  |

|Figure 13: The HotSpots collection | |

|defines the clickable areas on an | |

|ImageMap. | |

Select the type of hotspot from the Add button dropdown and click Add. You use a single set of x and y coordinates to define Rectangle and Circle hotspots while you must use a string of x and y coordinates to define polygon hotspots. The HotSpotMode property specifies the behavior for the hotspot. The Postback setting causes a postback to occur, and the Navigate setting causes a redirect to the page specified in the NavigateURL property.

Master Pages

Master pages provide the ability to define page templates on which you can base other pages, giving you—in effect—visual web page inheritance. Pages based on a master page, referred to as a content page, do not technically inherit the master page settings. Instead, combines the master page and the content page to form the resulting page (see Figure 14). The power lies in the fact that visual and program code changes made to the master page are immediately reflected in the content pages based on the revised master. Web site projects can contain more than one master page and you can embed a master page within another master page.

|[pic] |  |

|Figure 15: Select the Master Page item type to create a master page. | |

To create a master page you simply create a new page of type master page (see Figure 15). If you look at the HTML source for the master page you'll see the @Master directive, which defines the master page. The page parser uses the @Master tag attributes to create and compile the page:

The attributes for the @Master should look familiar. You typically see these same attributes on the @Page directive.

|[pic] |  |

|Figure 16: A master page is comprised of| |

|HTML, web controls, and one or more | |

|ContentPlaceHolders. | |

Just because creating the master page is easy that doesn't mean getting to the final layout is. This is where the talented graphics people come in handy. Unfortunately for this article you're stuck with my graphics skills. In Figure 16 and Listing 1 you can see that the page contains a table for layout, some simple background colors, a company logo, and some text. You should note the key item in the HTML code—the .

I have only one ContentPlaceHolder on my master page at the moment. I could have added more but one will do for now. With the master page created it's time to move on to creating the content Web Forms based on my master page.

To create a content page based on a master page you can simply click a checkbox and select the master page to use. I deleted the Default.aspx created when I created the project since I want to use Default.aspx as the name of my first content page. Go ahead and add a new Web Form by right-clicking on the project name to display the shortcut menu and select "Add New Item.' Select Web Form from the list of installed templates, enter the name of the form, Default.aspx in this case, and check the "Select master page" checkbox (see Figure 17). Click Add to display the "Select a Master Page" dialog box, which lets you select the master page to use with the new content page. The new content page will display, and the content inherited from the master page will appear grayed out and disabled (see Figure 18).

|[pic] |[pic] | |

|  |  | |

| | | |

|Figure 17: Check the "Select master page" |Figure 18: Master page content is disabled | |

|checkbox to create a content page. |while designing the content page. | |

| | | |

| | | |

Click the Source tab on the bottom of the design surface to reveal the HTML source for the page:

The MasterPageFile attribute on the @Page directive signifies which master page the current page works with. As you can see, there isn't much there. Key elements are the MasterPageFile argument in the @Page reference and the control. The controls define where to display content for the page and are directly tied to the specific ContentPlaceHolder control on the master page through the ContentPlaceHolderID property.

You can add content to a control by dragging and dropping controls into the control or manually via HTML coding. Launch the project to see how the master page will look when it renders.

Now that the fundamentals regarding how things look are out of the way, let me tackle a few coding issues you may run into. For example, master pages support the same events that a regular page supports, which means you can add code to the event handler for the Load event on the master page. Yes, you can add code to the same event handler in the master as well as the content page. Which code runs? The answer is both.

Event firing order becomes critically important when you add event handling code to master pages and the content forms based on them. The following events occur when renders a page. I've listed these events in the order in which they occur.

• Page Child Controls Initialize

• Master Page Initializes

• Content Page Initializes

• Master Page Loads

• Master Page Child Controls Load

• Content Page Child Controls Load

• Content Page Load Complete

|[pic] |  |

|Figure 19: The page event firing order | |

|determines when specific events will be | |

|raised. | |

In my example for this article I created the EventFiringOrder.aspx form containing a single label to help demonstrate when events occur. I added code to the appropriate event handlers in both the CoDeASPNET20 master page (see Listing 2) and the EventFiringOrder.aspx content page (see Listing 3). When you launch the form you can see the order in which the events occurred (see Figure 19).

Another issue related to working with master pages is: How do you programmatically access controls located on the master page from within a content page? The Master object provides a reference to the master page and is used to access master page attributes. Suppose you want to manipulate the value displayed in a textbox located on the master from within the content page. One approach would be to use the FindControls method on the Master object to locate a reference to the textbox:

Protected Sub Page_LoadComplete( _

ByVal sender As Object, _

ByVal e As System.EventArgs) _

Handles Me.LoadComplete

Response.Write(

"EventFiringOrder.aspx Load Complete")

Me.Label1.Text = _

CType(Master.FindControl("Textbox1"),

TextBox).Text

End Sub

While this approach works, it is late bound, meaning that you don't get IntelliSense assistance and it is not strongly typed. Alternatively, you can create a property on the master page that references the textbox and access the Text property from within the content page:

Partial Class WhatsNewIn20

Inherits System.Web.UI.MasterPage

Public Property DateTextBox() As TextBox

Get

Return TextBox1

End Get

Set(ByVal value As TextBox)

TextBox1 = value

End Set

End Property

...

To reference properties on the master page from the content page, you need to add the @MasterType directive to the content page:

To access the public properties on the master page from the content page you just use the Master object and reference the property as you would any other property exposed by the Master object:

Protected Sub Page_LoadComplete( _

ByVal sender As Object, _

ByVal e As System.EventArgs) _

Handles Me.LoadComplete

Response.Write(

"EventFiringOrder.aspx Load Complete")

Me.Label1.Text = Master.DateTextBox.Text

End Sub

So how do you specify the master page to use at run time? You can change the MasterPageFile attribute of the @Page directive at design time to specify which master page to use. That is great at design time but what if—based on some criteria only available at run time—you want to specify which master page to use? Knowing the content page events and their firing order comes into play here. The content page's PreInit event fires first, and at that point there will not yet have been any master page activity. Setting the content page's MasterPageFile property in the PreInit event gets the job done:

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download