Understand and extend the site navigation system in ASP. NET 2.0

Source: Internet
Author: User
Understand and expand the site navigation system in ASP. NET 2.0 released on: 2006-3-15 | updated on: 2006-3-15

David gristwood
Developer & platform group, Microsoft

Applicable:
Microsoft ASP. NET 2.0 (Beta 2)

Abstract:ASP. NET 2.0 website navigation system is built on a powerful and flexible architecture. This architecture is designed to make it scalable. This article explores the architecture of the site provider and provides an example provider that exposes the file system as the site navigation data source, replacing the standard web. sitemap XML file.

Download the example here.

Content on this page
Introduction
Understanding ASP. NET 2.0 Navigation System
Navigation controls
Use Navigation System
Implement your own site map provider
A folder site map provider
Summary

Introduction

Most Web sites use some form of visualized navigation to help users easily browse the site and find the information and web pages they need. Although different sites have different sensory effects, they usually use the same basic element-in the form of navigation bar or menu list, allowing users to locate the specific location of the web site.

ASP. NET 1.x provides little ready-to-use support for site navigation. As a result, many developers and web designers neither build their own navigation systems nor buy third-party controls to meet their needs. ASP. NET 2.0 has improved this by introducing a navigation system using a plug-in framework that can publish site hierarchies and insert controls for this new model, therefore, it is easy to construct a high-quality menu and navigation system.

This article describes the working principle of the ASP. NET 2.0 navigation system and shows how to scale it-not just using simple XML files (the default mechanism used in Visual Studio 2005 ).

Back to Top

Understanding ASP. NET 2.0 Navigation System

ASP. NET 2.0 is designed to create an excellent navigation model that attracts developers and web site designers. In addition, it also aims to create an architecture that provides scalability, which can flexibly meet a wide range of needs. The system is based on a provider model that runs throughout the ASP. NET 2.0 Framework. The ASP. NET 2.0 Framework provides a standard mechanism for inserting different data sources.

The ASP. NET 2.0 navigation framework can be divided into several parts:

Web navigation controls (menu, Treeview, and sitemappath) used by developers on actual web pages ). These controls can be customized to change the sensory effect.

The sitemapdatasource control bound to the Treeview and menu navigation controls provides an abstraction layer between the Web navigation controls and the underlying providers of navigation information.

The site map provider is a plug-in provider that exposes the actual information about the Web site layout. ASP. NET provides a provider xmlsitemapprovider, which uses an XML file with a specific structure as its data storage.

This layered architecture creates more loose coupling between the underlying site hierarchy and the controls on the web site, providing greater flexibility. With the continuous development of the site, it is easier to implement architectural and design changes.

The following table describes the relationship between the provider and the control.

Figure 1. Navigation Architecture

For the navigation system, the data source describes the hierarchy of the Web site pages that can be located by the user and how the information is displayed to the user. It is referenced as a site map. The layout of a simple Web site can be as follows:

HomeProductsProduct AProduct BProduct CLatest OffersContact UsEmailVisit us
Back to Top

Navigation controls

It is important to understand how developers interact with the internal working mechanism of the navigation system. The most common method is to use three new navigation controls in ASP. NET 2.0. Multiple Web navigation controls can exist on a site or page. For example, the Main Menu Control is placed on the left side of the page, and the other menu control is placed on the top of the page, we can program one navigation control to control another on the page, or allow them to operate independently.

The navigation system is usually used with the master page function. The master page function is also a new function provided in ASP. NET 2.0. By placing the navigation control on the master page of the site, you can ensure that the whole site has a unified sensory effect. However, the navigation function and the master page function are independent of each other.

The three new Web controls are:

Menu Control-it provides a traditional navigation interface, usually along one side of the web site or across the top. It can display any number of nested sub-menus, and when the user's mouse is suspended on a certain item, any number of optional sub-menus can be displayed.

Figure 2. Menu Control

Treeview control-it provides a vertical tree user interface, which can be expanded and collapsed by selecting a single node. It also provides the checkbox function for selecting certain items.

Figure 3. Treeview Control

Sitemappath control-it is usually referenced as a "breadcrumb" control because it can track users' locations within the site hierarchy. It displays the current location as a path, usually from the home page to the current location. Therefore, it is easier for users to understand their location and locate other pages in the path.

Figure 4. sitemappath Control

From the perspective of architecture, menu controls and Treeview controls are somewhat similar. The main difference between them is that the programming and display methods are different. Therefore, they have their own unique sensory effects. For more information about these two controls, see the msdn article introducing the ASP. NET 2.0 Treeview and menu controls. It is worth noting that although the most common cases of using menu controls and Treeview controls are inseparable from site navigation, they can also be used in non-Navigation situations, which need to be selected by the user.

The sitemappath (or "breadcrumb") controls are slightly different. It uses sitemapprovider directly, instead of the sitemapdatasource control used by The Menu Control and Treeview control. This shows that it is a more targeted control inside the navigation system. Therefore, there is less theoretical basis for extending its functions to non-Navigation scenarios.

Back to Top

Use Navigation System

One of the simplest ways to understand how site navigation works is to access it directly within an application rather than through a web control. The following code example shows how to interact with the sitemap object model to display some hierarchical site information.

<%@ Page Language="C#" %><script runat="server">private void Page_Load(object sender, System.EventArgs e){this.Label1.Text = "Current Page Title : " +SiteMap.CurrentNode.Title;if(SiteMap.CurrentNode.ChildNodes > 0) {this.HyperLink1.NavigateUrl =SiteMap.CurrentNode.ChildNodes[0].Url;this.HyperLink1.Text =SiteMap.CurrentNode.ChildNodes[0].Title;}}</script>

The navigation system converts the site map model into a series of nodes calledSitemapnodesIn a tree structure, each node usually represents a page on the web site that the user can locate (some nodes may be just placeholders of child pages, or similar, does not have web pages ).

SitemapnodeThe class has some attributes and methods, the most important of which are:

Title-Text displayed when the node is displayed through a Web Control

URL-Sitemapnode indicates the actual page URL in the Web site.

Description-Tooltip displayed when you hover your mouse over an HTML page Node

SitemapnodeClass also has some properties used to save the associations between various sitemapnodes. These associations describe the structure of the Site Map (Childnodes,Nextsibling,Previussibling,ParentnodeAnd so on ).

Back to Top

Implement your own site map provider

As mentioned above, ASP. NET 2.0 released a navigation data storage provider named xmlsitemapprovider, which is a default provider familiar to most developers. The provider uses data in an XML file that represents sitemapnodes. When Visual Studio 2005 is used, if you add a new site map to a web project, a web project is created by default. sitemap file, and fill in according to the following template format.

<siteMapxmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" ><siteMapNode url="" title=""  description=""><siteMapNode url="" title=""  description="" /><siteMapNode url="" title=""  description="" /></siteMapNode></siteMap>

You can see at a glance that the core sitemapnodes attribute (Title,URLAndDescriptionIs the attribute in the web. sitemap XML architecture, and the tree structure (parent, child, etc.) is represented by nested sitemapnodes.

This is a simple and refined method for processing site map information, and is more than enough for many web designers. However, the scalability of the ASP. net provider model does not mean that you can write your own provider. There are three possible reasons to create a custom site map provider:

The site map information is stored in a non-XML file data source, such as a database or directory service.

The site map information is used in XML format, but the architecture used is different from that used by web. sitemap.

A Dynamic Site map structure is required. This structure must be constructed at runtime, or a custom view that cannot be processed by security tailoring is required.

To implement your own site map provider, you needSitemapproviderA custom provider class is derived from an abstract class. AlthoughSitemapproviderClass has about 20 abstract or virtual methods, but only a few of your custom site map providers need to be rewritten or implemented.

If the data storage used by your custom site map provider is similar to the Web. sitemap XML architecture of the default xmlsitemapprovider, selectStaticsitemapproviderClass, which providesSitemapproviderAnd vice versa as the actualXmlsitemapproviderThe base class of the class.

Your class must at least implement the following methods:

Findsitemapnode-returns a sitemapnode corresponding to a specific URL.

Getchildnodes-returns a set of subnodes of a specific sitemapnode.

Getparentnode-returns the parent node of a specific sitemapnode.

Getrootnodecore-returns the root node of all nodes currently managed by the current provider.

You should also overrideInitializeMethod, in the call base classInitializeThen execute your own initialization in this method.

If necessary, you can rewrite some node-related attributes to construct a more complex model that represents a site map:

Sitemapnode-return the node mapped to the current httpcontext URL.

Rootnode-return the node at the root of the storage.

Rootprovider-returns the root provider to allow chained providers.

These attributes and methods represent the agreements between sitemapprovider, menu/Treeview control (through sitemapdatasource), and sitemappath control. In either of the following cases, the interaction occurs: the control requests to fill in the display of the required information, and the user uses the site to navigate to track the current location in the site navigation. It is an event-driven model. During the interaction process, the navigation system calls the provider.

If you write your own provider, you need to decide whether sitemapnodes is read-only or writable.-If it is writable, you need to consider thread security and lock the update code when appropriate, so as to ensure the implementation is thread-safe, because ASP. net schedules requests through a thread pool, so a thread pool will be accessed by multiple threads.

A more detailed question is about performance and scalability. It is not uncommon for a web site to use several navigation controls or the storage capacity of the underlying navigation data is large. Therefore, you must ensure that the provider can respond, this affects design issues, including the best algorithms for storing and retrieving data and the potential impact of caching.

Security issues also need to be considered. The general requirement of a web site is to allow members or other authenticated users to view a specific page, while ASP.. NET 2.0 role management provides a well-defined approach to restrict access to web files based on security roles. This feature is extended to the site navigation system through a mechanism called security tailoring. Security tailoring forces URL and file authorization to be applied when you attempt to access the page. DefineRolesAttribute is used to expand access to this node-if you are inRolesIf you are not one of these roles, the node will be returned. If you are not one of these roles, the URL and file authoriation check will be executed. For xmlsitemapprovider, addRoles = "managers"The Type attribute determines whether the node can be viewed in the site map. When writing your own site map providerIsaccessabletouserMethod. It returns a Boolean value based on the user's role to indicate whether the node is available to the user. Derived providers can use the base classSitemapprovider. To support security, a site map must provide a method to store the information.

Back to Top

A folder site map provider

The examples in this article expose the subdirectories of a web site to actual site maps, which enables the web site navigation to be directly mapped to the folder structure. Such a web site structure model is not uncommon. This example focuses on how to design and construct a site map provider, in which case it is not intended to cover all possible "Edge Conditions" in terms of industry advantages ". The appropriate positions of these trade-offs have been emphasized in this article.

The sample provider uses the subdirectories of the web site for Recursive enumeration and checks Each folder (except the app _ * and bin directories, which are Asp. NET 2.0 special directory) whether there is a default. aspx file. If this file exists, the sample provider adds it to the site map and uses the name containing the folder as the menu description. This example is extended so that each directory not only supports default. aspx items, but also stores a date tooltip in a text file in the directory if necessary, which is relatively simple to implement.

The core code of the provider is as follows.

[AspNetHostingPermission(SecurityAction.Demand, Level =AspNetHostingPermissionLevel.Minimal)]public class FolderSiteMapProvider : SiteMapProvider{private SiteMapNode rootNode = null;// root of treeprivate Hashtable urlHash = null;// hash table based on URLprivate Hashtable keyHash = null;// hash table based on keystring defaultPageName = "Default.aspx";// only look for this file in each subdirectorystring defaultTitle = "Home";// description of root node// override SiteMapProvider Initializepublic override void Initialize(string name,NameValueCollection attributes){// do base class initialization firstbase.Initialize(name, attributes);// our custom initializationurlHash = new Hashtable();keyHash = new Hashtable();// get web site infostring startFolder = HttpRuntime.AppDomainAppPath;string startUri =Uri.EscapeUriString(HttpRuntime.AppDomainAppVirtualPath);// want canonical format of URI// Create root nodestring key = startFolder;string url = startUri + @"/" + defaultPageName;rootNode = new SiteMapNode(this, key, url, defaultTitle);RootNode.ParentNode = null;urlHash.Add(url, rootNode);keyHash.Add(key, rootNode);// populate entire siteEnumerateFolders(rootNode);}// Retrieves a SiteMapNode that represents a pagepublic override SiteMapNode FindSiteMapNode(string rawUrl){if (urlHash.ContainsKey(rawUrl)){SiteMapNode n = (SiteMapNode)urlHash[rawUrl];return n;}else{return null;}}// Retrieves the root node of all the nodes//currently managed by the current provider.// This method must return a non-null nodeprotected override SiteMapNode GetRootNodeCore(){return rootNode;}// Retrieves the child nodes of a specific SiteMapNodepublic override SiteMapNodeCollectionGetChildNodes(SiteMapNode node){SiteMapNode n = (SiteMapNode)keyHash[node.Key];// look up our entry, based on keyreturn n.ChildNodes;}// Retrieves the parent node of a specific SiteMapNode.public override SiteMapNode GetParentNode(SiteMapNode node){SiteMapNode n = (SiteMapNode)keyHash[node.Key];// look up our entry, based on keyreturn n.ParentNode;}// helper functions . . .//  . . .}

When the provider uses itsInitializeWhen the method is called, the sample provider generates a folder list, but does not refresh the list. Therefore, it does not check the new folders added at any time, which is unreasonable for the web site of a product.

It does not implement security tailoring, so all subdirectories are visible. However, it is very easy to achieve security tailoring, as longFindsitemapnode,GetchildnodesAndGetparentnodeAdd a base class to the MethodIsnodeaccessibleYou can call the method,IsnodeaccessibleThe method automatically obtains the advantages of any file authorization rules configured for the web site.

The provider can represent the underlying storage in any way internally, but because it usesSitemapnodeClass interacts with the navigation system, especially because the directory hierarchy matches the node hierarchy, so it makes sense to use these methods internally. It also maintains two hash tables, one with the node URL as the keyword, and the other with the node keyword (Folder name) as the keyword, which supports fast node query. In this example, it makes sense to save all this information in the memory, because it can maintain a simple programming model and very fast query speed; however, for a large site with thousands of folders, it may be worthwhile to study a mechanism to store all the information not in memory.

To keep simple code, nodes are not read-only. In a real provider with industry advantages, when the application cannot add or modify the internal list of site map nodes, each node and the entire set are marked as read-only.

The private helper function is used to construct a folder hierarchy, as shown in the following code example.

private void EnumerateFolders(SiteMapNode parentNode){// create a node collection for this directorySiteMapNodeCollection nodes = new SiteMapNodeCollection();parentNode.ChildNodes = nodes;// get list of subdirectories within this directorystring targetDirectory = parentNode.Key;// we use the key to hold the file directorystring[] subdirectoryEntries =Directory.GetDirectories(targetDirectory);foreach (string subdirectory in subdirectoryEntries){// search for any sub folders in this directorystring[] s = subdirectory.Split('\\');string folder = s[s.Length-1];string tmp = String.Copy(folder);tmp = tmp.ToLower();// avoid any case sensitive matching issues// check for App_ and bin directories, and don't add themif (tmp.StartsWith("app_"))continue;if (tmp == "bin")continue;string testFileName = subdirectory + @"\" + defaultPageName;if (File.Exists(testFileName)){// create new nodestring key = subdirectory;string url = CreateChildUrl(parentNode.Url, folder);string title = folder;SiteMapNode n = new SiteMapNode(this, key, url, title);n.ParentNode = parentNode;// add it into node collection and tablenodes.Add(n);urlHash.Add(url, n);keyHash.Add(key, n);// and enummerate through this folder nowEnumerateFolders(n);}}}

When the provider enumerates in subdirectories, it createsSitemapnodeClass, and set itsKey,URLAndTitleAttribute. It also fills every subnodeChildnodesProperty, which is a sitemapnodecollection, andParentnodeThe property is directed back to the parent node. It also adds each node to the hash table for quick query.

Once these operations are completed, the provider must use the web. config file for configuration. The following items need to be added to <System. Web>.

<system.web>. . .<siteMap defaultProvider="SimpleProvider"><providers><add name="SimpleProvider"type="Test.SimpleProvider"/></providers></siteMap>. . .</system.web>
Back to Top

Summary

The goal of this article is to help you understand and correctly evaluate the ASP. NET 2.0 website navigation system and understand the principles of collaboration between different elements. The code example shows how to expand the architecture by constructing your own site map provider, which uses any data source to define the site hierarchy.

About the author

David gristwood works with Microsoft's UK developers and platform groups most of his time working with customers and partners to help them design and build solutions that fully utilize the Microsoft. NET platform. He also often speaks at meetings and seminars.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.