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

Professional Visual Studio 2005 (2006) [eng]

.pdf
Скачиваний:
132
Добавлен:
16.08.2013
Размер:
21.9 Mб
Скачать

Additional Web Techniques

Chapter 41 introduced the basic concepts for web projects, highlighting some of the new controls introduced with .NET 2.0 and Visual Studio 2005. Actually, those were just the tip of the iceberg, with many other features being made available to you while creating web applications. This chapter describes some of the more useful additions that require a little more forethought when implementing, including the Sitemap control and how to use the new Web Parts functionality.

In addition, this chapter contains a discussion on building custom controls, and examines the templatization of individual controls for use elsewhere in your web site.

Web Development Revisited

As the previous chapter showed you, while ASP.NET 1.0 revolutionized the way you can build solutions for the Internet, the new features available in ASP.NET 2.0 and Visual Studio 2005 have matured to the point where their use becomes, without question, commercially viable. You are now able to create and maintain development projects at almost any location, including remote FTP servers, enabling you to easily deploy and manage web solutions.

The introduction of an array of user-based controls means that building web sites that incorporate login/logout functionality, and viewing customization based on user roles, is now straightforward, while the new dialogs for choosing colors, styles, and formats are more easily identified with the way web sites are traditionally created.

In addition to these extra controls and design-time enhancements, developing web solutions is made even simpler with a built-in temporary server for easily testing your pages, and additional support is provided with other easy to use features, such as being able to run and debug from any page in the site.

Chapter 42

However, you can take advantage of additional features, both in the IDE and with web development in general, to make the creation of web projects even easier. One such feature is the View menu, which is expanded with extra commands when designing a web site.

The modifications made to the View menu of the IDE are a great example of what Visual Studio does to contextually provide you with useful features depending on what you’re doing. When you’re editing a web page in Design view, additional menu commands become available for adjusting how the design surface appears (see Figure 42-1).

Figure 42-1

For example, when Visible Borders is toggled on via the View menu, it will draw gray borders around all container controls and HTML tags such as <table> and <div> so you can easily see where each component resides on the form.

When creating Windows applications, if you add a nonvisual control such as a Timer to a form’s design surface, a tray area below the form is displayed with an icon for the control so you can easily get to it. With web applications, because the tray area is already in use to show what editing mode you’re in as well as a breadcrumb trail of where you are in the HTML, nonvisual controls are hidden from view by default. Activating the Non Visual Controls option shows a large placeholder icon in the space where the nonvisual control is situated in the HTML markup, so you can find where they’ve been added and easily access their property list.

The third option that configures the way your design-time view appears shows the details about every tag present in the HTML markup. To show these additional markers, use the View Details menu command. However, as illustrated in Figure 42-2, showing these visual indicators can affect the way the layout appears in the designer, rendering an accurate representation of how the web page will look next to impossible.

578

Additional Web Techniques

Figure 42-2

The view details option is best suited for finding a rogue tag that isn’t in the right place, so using the keyboard shortcut of Ctrl+Shift+Q to quickly toggle the indicators on and off is the most efficient way to use it.

The Sitemap

The sitemap is a method to provide sitewide navigation to your web applications. Unfortunately, to implement sitemap functionality into your projects, you first have to manually create the site data and keep it up-to-date as you add or remove web pages from the site. Once you have created the sitemap file, you can then use it as a Data Source for a number of web controls, including the SiteMapPath, which automatically keeps of where you are in the site hierarchy, as well as the Menu and TreeView controls, which can present a custom subset of the sitemap information.

web.sitemap

The first task you must perform when implementing sitewide navigation is to create an XML representation of your site’s structure. Using XML to store the structure is a logical way of keeping the data because it can store information of a hierarchical nature. This default name for this file is web.sitemap but you can change it in the Web.config file if you need to follow another naming convention.

579

Chapter 42

The Web.config file should have a subnode within the <system.web> node called <siteMap> that defines the kind of provider to be used for the site information. A typical <siteMap> node structure looks like this:

<system.web>

<siteMap defaultProvider=”XmlSiteMapProvider” enabled=”true”> <providers>

<add name=”XmlSiteMapProvider”

description=”SiteMap provider which reads in .sitemap XML files.” type=”System.Web.XmlSiteMapProvider, System.Web,

Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” siteMapFile=”web.sitemap” securityTrimmingEnabled=”true”/>

</providers>

</siteMap>

</system.web>

Change the value of the siteMapFile attribute to the desired filename, and save the Web.config file to update the project.

The sitemap XML file follows a simple syntax. You first create a root node of <siteMap> that contains a single node of type <siteMapNode>. Within this top-level <siteMapNode>, you then add a <siteMapNode> for each page you want to map in whatever hierarchical form you want. This means you can create a hierarchical structure to your site that has no resemblance to the real directory and page structure of your projects (which is a good thing because you can keep the user experience separate from the design-time experience).

You should set the following attributes for each <siteMapNode>:

title: Used to display a readable string in the SiteMapPath control and any other controls that use the web.sitemap file.

url: The page URL relative to the root space of the web, so if your page were located at http://www.wrox.com/pages/ThisPage.aspx, then the url attribute value would be pages/ThisPage.aspx. Omitting the url attribute produces a node in the visual controls that cannot be clicked, but can still be used for formatting and logical division of the site.

description: A longer description of what the page contains. Not used in most cases, it can be handy for automatically producing sitewide documentation.

The following example illustrates the relationship between physical location, desired virtual location in the site hierarchy, and the corresponding web.sitemap file. You have the following pages in your web project:

Default.aspx: The main home page of the web site

ContactUs.aspx: The contact details of the company

Products/ProductView.aspx: A view page of an individual page

Products/ProductList.aspx: A full list of products

CustomerLogin.aspx: The page where the customer registers and logs in to the site

CustomerProfile.aspx: A page where the customer can modify his or her details

580

Additional Web Techniques

You want to present the site information so that the navigational structure appears as shown in Figure 42-3.

Home Page

Contact Us

Product List

Product View

Customers

Login/Register

Your Profile

Figure 42-3

To implement such a hierarchy, you would need to create a web.sitemap file similar to the following listing:

<?xml version=”1.0” encoding=”utf-8” ?> <siteMap>

<siteMapNode title=”Home Page” url=”Default.aspx”> <siteMapNode title=”Contact Us” url=”ContactUs.aspx” />

<siteMapNode title=”Product List” url=”Products/ProductList.aspx” > <siteMapNode title=”Product View” url=”Products/ProductView.aspx” />

</siteMapNode>

<siteMapNode title=”Customers” >

<siteMapNode title=”Login/Register” url=”CustomerLogin.aspx” /> <siteMapNode title=”Your Profile” url=”CustomerProfile.aspx” />

</siteMapNode>

</siteMapNode>

</siteMap>

When creating the web.sitemap file you must remember to keep it up-to-date. Unfortunately, Visual Studio 2005 doesn’t have any automated way of doing this, so if you rename or remove a page, you have to also remove its entry from the sitemap file. Similarly, if you add new pages to your site, they won’t be included in any sitemap-based user interface controls until you also add them to the sitemap layout.

The SiteMapPath Control

Once you have your site hierarchy defined, the easiest way to use it is to drag and drop a SiteMapPath control onto your web page design surface (see Figure 42-4). This control automatically binds to the default sitemap provider, as specified in the Web.config file, to generate the nodes for display.

Figure 42-4

581

Chapter 42

The SiteMapPath control works as a breadcrumb trail of the site, meaning it only displays the current page the user is on, tracking back up the hierarchy to display the parent nodes, right up to the root node. Figure 42-5 shows how this control might look when a user is viewing the Product View page.

Figure 42-5

As you can see, the only links visible are the root node tracking directly down to the page being viewed. In this case, the only other page is the Product List page, which was defined in the web.sitemap file as being the parent of the Product View page.

The SiteMapResolve Event

Sometimes you might want to modify the URLs that are generated from the sitemap to include additional details. This is usually the case when you need to specify a parameter on the URL that will redirect users to a specific view of the page. For example, if the sample site divides the product list into Product Groups, it may include an optional parameter containing the product group, such as www

.myproductsite.com/Products/ProductList.aspc?ProductGroupID=3.

The basic view presented by the SiteMapPath control (and any other controls that use the sitemap as their Data Source) does not include these additional parameters, as they are not specified in the web.sitemap configuration file. However, you can customize the properties of each siteMapNode as it is rendered by handling the SiteMapResolve event.

To handle the SiteMapResolve event, you must first create a subroutine that will be executed when the event is raised. This event has the following syntax:

Private Function MySiteMapResolveEventHandler(ByVal sender As Object, _ ByVal e As SiteMapResolveEventArgs) As SiteMapNode

End Function

You then need to connect this function to the event by using an AddHandler event in the Load event of the page. You use AddHandler in the same way you would when adding handlers in Windows applications.

To customize the appearance of the nodes as they display on the page, you need to clone the current node to a new SiteMapNode object. This enables you to modify the contents of the node and its parents (which you cannot do to the permanent SiteMapNode). After you modify the properties of the node and its parents, you then return this cloned version of the SiteMapNode from the event handler function so that the new details are used.

582

Additional Web Techniques

The following listing is a more complete code sample that could be used to customize the Product List node when viewing an individual product:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load

AddHandler SiteMap.SiteMapResolve, AddressOf Me.TweakUrls End Sub

Private Function TweakUrls(ByVal sender As Object, _ ByVal e As SiteMapResolveEventArgs) As SiteMapNode

Dim myCurrentNode As SiteMapNode = SiteMap.CurrentNode.Clone(True) Dim MyTraversingNode As SiteMapNode = myCurrentNode

Dim ProductGroupID As Integer = DetermineProductGroup()

MyTraversingNode = MyTraversingNode.ParentNode

If Not (MyTraversingNode Is Nothing) Then

MyTraversingNode.Url = MyTraversingNode.Url & “?ProductGroupID=” & _

ProductGroupID.ToString()

MyTraversingNode.Title = “Product List (Group “ & ProductGroupID.ToString _

& “)”

End If

Return myCurrentNode

End Function

The function TweakUrls is created with the same signature as the event it will handle. The Page_Load routine is then modified so that this function is hooked up to the event when the page loads. When the event is raised, the TweaKUrls function is called, which in turn calls the DetermineProductGroup function to retrieve the corresponding Product Group ID for the currently displayed product.

The DetermineProductGroup function is not shown in this example, but could access a database to determine the correct value, or simply extract it from the currently displayed product’s key value.

Once the ID value is determined, the code gets the parent node of the current node. As you’ve seen previously, the parent node in this structure equates to the ProductList.aspx page. It then modifies the Url and Title properties of this node to contain information about the ID, and then finally returns the temporary SiteMapNode object. The result is shown in Figure 42-6.

Figure 42-6

583

Chapter 42

The Product List title has been changed to include the product group to which the product belongs. Notice that the status bar text indicating the URL has also been updated, indicating that when this link is clicked, the user will navigate to a specific group of products.

The Web Menu Control

While the SiteMapPath control displays only the breadcrumb trail leading directly to the currently viewed page, at times you will want to display a list of pages in your site. The Menu ASP.NET control can be used to achieve this, and has modes for both horizontal and vertical viewing of the information.

Menu controls work slightly differently than SiteMapPath controls in that you need to associate them with a Data Source, and they can control how much of the data is displayed. To add menu functionality to your site, first add a SiteMapDataSource control to the page. As you might expect, this control is found in the Data category in the Toolbox.

This is a nonvisual control, so you might need to toggle invisible controls on with View Non Visual Controls to see it on the design surface.

By default, the SiteMapDataSource uses the web.sitemap configuration file in its entirety, starting from the top-level root node and using all children nodes. However, you have two options to fine-tune this behavior so that the Data Source is only populated with a subset of the hierarchy: StartingNode Url and StartingNodeOffset.

StartingNodeUrl enables you to set a specific starting point within the sitemap information. The Data Source will only contain nodes that represent that starting page and any of its children (and their children, and so on). Use the tilde (~) character to specify the root of the website — for example, specifying ~/Products/ProductList.aspx would result in a Data Source that only contains the Product List node and its children (which in this sample site is the Product View page only).

This enables you to define a comprehensive sitemap for your entire web application, and then provide custom views of the site depending on where the user is.

The other way to filter the node information is to use StartingNodeOffset. Rather than specify a specific page to start from, this property tells the Data Source component to only include nodes for a certain level and down, excluding any nodes that are further up the chain. The value is zero-based, so a value of 1 will ignore the top-level node but include everything else. For the sample site, this would mean all pages but the home page are included.

When you have configured the SiteMapDataSource component to return the site information you want to use, place a Menu control on the design surface and position and format it to suit the rest of your site. To connect the Menu to the Data Source, set the DataSourceID property to the name of your SiteMap DataSource control from the drop-down list shown in the Properties window.

As soon as you change this value, the appearance of the Menu control is updated to reflect the contents of the Data Source, so you can preview how it will look at design time. The default view of the Menu control shows the root node only and orients the menu vertically.

584

Additional Web Techniques

To change the amount of the sitemap that is displayed in the menu’s static area, set the StaticDisplay Levels property to the depth you require. If you want the static portion of the menu to appear horizontally, change the Orientation property. Figure 42-7 shows the original Product View page with the SiteMapPath control, along with two new Menu controls.

The horizontal menu had its StaticDisplaylevels property set to 2 so it would display the Home Page link, along with any pages that were on the second level of the sitemap, while the vertical map used a StaticDisplayLevels value of 3 to show all pages.

The menu automatically generates the client-side script required for menus to pop out like the Customers submenu shown in Figure 42-7.

Figure 42-7

A great place to use the SiteMapPath and Menu controls is in a master page, which can then be used to pass the controls around for all your details pages, with the nodes displayed to users automatically updating based on which page they’re on.

Web Par ts

Another excellent feature added to Visual Studio 2005 is the capability to create Web Parts controls and pages so that your site can be divided into chunks that either you or your users can move around, and show and hide, to create a unique viewing experience. Web Parts for Visual Studio are loosely based on custom web controls but owe their inclusion in Visual Studio to the huge popularity of Web Parts in SharePoint Portals.

585