Understand and extend the site navigation system http://msdn.microsoft.com/zh-cn/library/aa479338.aspx 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 site providesProgramProvides a sample provider that exposes the file system as a 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 the top to understand the navigation system in ASP. NET 2.0
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 the two controls, seeArticleIntroducing 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 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. BelowCodeThe example shows how to interact with the sitemap object model to display part of the hierarchical and structured 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> <HTML>
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 the top page to 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 data storage and retrieval.AlgorithmAnd the potential role of the cache.
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 1: 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 + @ "/" + defapagpagename; rootnode = new sitemapnode (this, key, URL, defaulttitle); rootnode. parentnode = NULL; urlhash. add (URL, rootnode); keyhash. add (Key, rootnode); // populate entire partition (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 nodes (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.