Export (0) Print
Expand All

SiteMapProvider Class

Provides a common base class for all site map data providers, and a way for developers to implement custom site map data providers that can be used with the ASP.NET site map infrastructure as persistent stores for SiteMap objects.

Namespace:  System.Web
Assembly:  System.Web (in System.Web.dll)

public abstract class SiteMapProvider : ProviderBase

The SiteMapProvider type exposes the following members.

  NameDescription
Protected methodSiteMapProviderInitializes a new instance of the SiteMapProvider class.
Top

  NameDescription
Public propertyCurrentNodeGets the SiteMapNode object that represents the currently requested page.
Public propertyDescriptionGets a brief, friendly description suitable for display in administrative tools or other user interfaces (UIs). (Inherited from ProviderBase.)
Public propertyEnableLocalizationGets or sets a Boolean value indicating whether localized values of SiteMapNode attributes are returned.
Public propertyNameGets the friendly name used to refer to the provider during configuration. (Inherited from ProviderBase.)
Public propertyParentProviderGets or sets the parent SiteMapProvider object of the current provider.
Public propertyResourceKeyGet or sets the resource key that is used for localizing SiteMapNode attributes.
Public propertyRootNodeGets the root SiteMapNode object of the site map data that the current provider represents.
Public propertyRootProviderGets the root SiteMapProvider object in the current provider hierarchy.
Public propertySecurityTrimmingEnabledGets a Boolean value indicating whether a site map provider filters site map nodes based on a user's role.
Top

  NameDescription
Protected methodAddNode(SiteMapNode)Adds a SiteMapNode object to the node collection that is maintained by the site map provider.
Protected methodAddNode(SiteMapNode, SiteMapNode)Adds a SiteMapNode object to the node collection that is maintained by the site map provider and specifies the parent SiteMapNode object.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodFindSiteMapNode(HttpContext)Retrieves a SiteMapNode object that represents the currently requested page using the specified HttpContext object.
Public methodFindSiteMapNode(String)When overridden in a derived class, retrieves a SiteMapNode object that represents the page at the specified URL.
Public methodFindSiteMapNodeFromKeyRetrieves a SiteMapNode object based on a specified key.
Public methodGetChildNodesWhen overridden in a derived class, retrieves the child nodes of a specific SiteMapNode.
Public methodGetCurrentNodeAndHintAncestorNodesProvides an optimized lookup method for site map providers when retrieving the node for the currently requested page and fetching the parent and ancestor site map nodes for the current page.
Public methodGetCurrentNodeAndHintNeighborhoodNodesProvides an optimized lookup method for site map providers when retrieving the node for the currently requested page and fetching the site map nodes in the proximity of the current node.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetParentNodeWhen overridden in a derived class, retrieves the parent node of a specific SiteMapNode object.
Public methodGetParentNodeRelativeToCurrentNodeAndHintDownFromParentProvides an optimized lookup method for site map providers when retrieving an ancestor node for the currently requested page and fetching the descendant nodes for the ancestor.
Public methodGetParentNodeRelativeToNodeAndHintDownFromParentProvides an optimized lookup method for site map providers when retrieving an ancestor node for the specified SiteMapNode object and fetching its child nodes.
Protected methodGetRootNodeCoreWhen overridden in a derived class, retrieves the root node of all the nodes that are currently managed by the current provider.
Protected methodStatic memberGetRootNodeCoreFromProviderRetrieves the root node of all the nodes that are currently managed by the specified site map provider.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodHintAncestorNodesProvides a method that site map providers can override to perform an optimized retrieval of one or more levels of parent and ancestor nodes, relative to the specified SiteMapNode object.
Public methodHintNeighborhoodNodesProvides a method that site map providers can override to perform an optimized retrieval of nodes found in the proximity of the specified node.
Public methodInitializeInitializes the SiteMapProvider implementation, including any resources that are needed to load site map data from persistent storage. (Overrides ProviderBase.Initialize(String, NameValueCollection).)
Public methodIsAccessibleToUserRetrieves a Boolean value indicating whether the specified SiteMapNode object can be viewed by the user in the specified context.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodRemoveNodeRemoves the specified SiteMapNode object from the node collection that is maintained by the site map provider.
Protected methodResolveSiteMapNodeRaises the SiteMapResolve event.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public eventSiteMapResolveOccurs when the CurrentNode property is called.
Top

The StaticSiteMapProvider and XmlSiteMapProvider classes represent the default implementations of the abstract SiteMapProvider class. The XmlSiteMapProvider uses an XML file named Web.sitemap to store site map data. For more information on about the Web.sitemap file, see ASP.NET Site Maps.

The SiteMapProvider class supports the concept of a site map provider hierarchy, by declaring the RootProvider and ParentProvider properties. A SiteMapProvider can be a child or parent of another provider. This enables scenarios where different content areas of a site are owned or implemented by different development groups that maintain their own site maps and site map providers.

All SiteMapProvider objects are configured in the Web.config files. Any site map providers that are declared in these configuration files are loaded at run time and are used to load and process site navigation data. The SiteMap object, which keeps track of all the providers that are available to it through its Providers property collection, provides programmatic access to the navigation data that is managed by the providers. The following code example demonstrates the format that is used to declare a site map provider in a Web.config file.

<siteMap defaultProvider="<name>">
  <providers>
    <add
      name="<friendly name>"
      type="<fully qualified class name>, <assembly name (optional)>" 
      siteMapFile = "<file name>" />
  </providers>
</siteMap>

The site navigation data that is loaded by these providers is used by other components of the site map infrastructure, such as the SiteMapPath and TreeView controls, to display site map information for users.

If you implement your own site map provider, you can place the source file in the App_Code directory of your ASP.NET application, and then the assembly will be compiled automatically. You can also place your own site map provider in the Global Assembly Cache (GAC), and provide a fully-qualified reference to it in the Web.config file. For more information on compiler services, see Working with Assemblies and the Global Assembly Cache.

Notes to Inheritors

When you inherit from the SiteMapProvider class, you must override the following members: GetRootNodeCore, FindSiteMapNode, GetChildNodes, and GetParentNode.

TopicLocation
How to: Programmatically Enumerate Site-Map NodesBuilding ASP .NET Web Applications
How to: Configure Multiple Site Maps and Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server ControlsBuilding ASP .NET Web Applications
How to: Display Site-Map Data in Non-Hierarchical Web Server ControlsBuilding ASP .NET Web Applications
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications
How to: Implement ASP.NET Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Programmatically Enumerate Site-Map NodesBuilding ASP .NET Web Applications
How to: Configure Multiple Site Maps and Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server ControlsBuilding ASP .NET Web Applications
How to: Display Site-Map Data in Non-Hierarchical Web Server ControlsBuilding ASP .NET Web Applications
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications
How to: Implement ASP.NET Site-Map ProvidersBuilding ASP .NET Web Applications
How to: Add Simple Site NavigationBuilding ASP .NET Web Applications in Visual Studio

The following code example demonstrates how to write a class that implements the abstract SiteMapProvider class. This example includes only a sample SiteMapProvider and a sample text file that works with it. To run the example you also need an entry in the Web.config file and an .aspx page. You can find these in the documentation for the SiteMapDataSource.SiteMapProvider property.

The example uses a comma-delimited file that follows an expected structure to load sitemap information. The first line of the file represents the root node of the sitemap, and subsequent lines are subnodes. Each subnode identifies its parent node by URL. An example of a file that meets these criteria is shown below.

default.aspx,Home,MyCompany Home Page,
sale.aspx,Now On Sale,Check Out These Great Deals!,default.aspx
catalog.aspx,Online Catalog,Browse Our Many Great Items!,default.aspx

The SimpleTextSiteMapProvider provides example implementations of all the SiteMapProvider properties and methods.

using System;
using System.Configuration.Provider;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Security.Permissions;
using System.Web;

namespace Samples.AspNet.CS
{

  [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
  public class SimpleTextSiteMapProvider : SiteMapProvider
  {
    private SiteMapProvider parentSiteMapProvider = null;
    private string simpleTextProviderName = null;
    private string sourceFilename = null;
    private SiteMapNode rootNode = null;
    private ArrayList siteMapNodes = null;
    private ArrayList childParentRelationship = null;


    // A default constructor. The Name property is initialized in the 
    // Initialize method. 
    public SimpleTextSiteMapProvider()
    {
    }
    // Implement the CurrentNode property. 
    public override SiteMapNode CurrentNode
    {
      get
      {
        string currentUrl = FindCurrentUrl();
        // Find the SiteMapNode that represents the current page.
        SiteMapNode currentNode = FindSiteMapNode(currentUrl);
        return currentNode;
      }
    }

    // Implement the RootNode property. 
    public override SiteMapNode RootNode
    {
      get
      {
        return rootNode;
      }
    }
    // Implement the ParentProvider property. 
    public override SiteMapProvider ParentProvider
    {
      get
      {
        return parentSiteMapProvider;
      }
      set
      {
        parentSiteMapProvider = value;
      }
    }

    // Implement the RootProvider property. 
    public override SiteMapProvider RootProvider
    {
      get
      {
        // If the current instance belongs to a provider hierarchy, it 
        // cannot be the RootProvider. Rely on the ParentProvider. 
        if (this.ParentProvider != null)
        {
          return ParentProvider.RootProvider;
        }
        // If the current instance does not have a ParentProvider, it is 
        // not a child in a hierarchy, and can be the RootProvider. 
        else
        {
          return this;
        }
      }
    }
    // Implement the FindSiteMapNode method. 
    public override SiteMapNode FindSiteMapNode(string rawUrl)
    {

      // Does the root node match the URL? 
      if (RootNode.Url == rawUrl)
      {
        return RootNode;
      }
      else
      {
        SiteMapNode candidate = null;
        // Retrieve the SiteMapNode that matches the URL. 
        lock (this)
        {
          candidate = GetNode(siteMapNodes, rawUrl);
        }
        return candidate;
      }
    }
    // Implement the GetChildNodes method. 
    public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
    {
      SiteMapNodeCollection children = new SiteMapNodeCollection();
      // Iterate through the ArrayList and find all nodes that have the specified node as a parent. 
      lock (this)
      {
        for (int i = 0; i < childParentRelationship.Count; i++)
        {

          string nodeUrl = ((DictionaryEntry)childParentRelationship[i]).Key as string;

          SiteMapNode parent = GetNode(childParentRelationship, nodeUrl);

          if (parent != null && node.Url == parent.Url)
          {
            // The SiteMapNode with the Url that corresponds to nodeUrl 
            // is a child of the specified node. Get the SiteMapNode for 
            // the nodeUrl.
            SiteMapNode child = FindSiteMapNode(nodeUrl);
            if (child != null)
            {
              children.Add(child as SiteMapNode);
            }
            else
            {
              throw new Exception("ArrayLists not in sync.");
            }
          }
        }
      }
      return children;
    }
    protected override SiteMapNode GetRootNodeCore()
    {
      return RootNode;
    }
    // Implement the GetParentNode method. 
    public override SiteMapNode GetParentNode(SiteMapNode node)
    {
      // Check the childParentRelationship table and find the parent of the current node. 
      // If there is no parent, the current node is the RootNode.
      SiteMapNode parent = null;
      lock (this)
      {
        // Get the Value of the node in childParentRelationship
        parent = GetNode(childParentRelationship, node.Url);
      }
      return parent;
    }

    // Implement the ProviderBase.Initialize property. 
    // Initialize is used to initialize the state that the Provider holds, but 
    // not actually build the site map. 
    public override void Initialize(string name, NameValueCollection attributes)
    {

      lock (this)
      {

        base.Initialize(name, attributes);

        simpleTextProviderName = name;
        sourceFilename = attributes["siteMapFile"];
        siteMapNodes = new ArrayList();
        childParentRelationship = new ArrayList();

        // Build the site map in memory.
        LoadSiteMapFromStore();
      }
    }
    // Private helper methods 

    private SiteMapNode GetNode(ArrayList list, string url)
    {
      for (int i = 0; i < list.Count; i++)
      {
        DictionaryEntry item = (DictionaryEntry)list[i];
        if ((string)item.Key == url)
          return item.Value as SiteMapNode;
      }
      return null;
    }

    // Get the URL of the currently displayed page. 
    private string FindCurrentUrl()
    {
      try
      {
        // The current HttpContext.
        HttpContext currentContext = HttpContext.Current;
        if (currentContext != null)
        {
          return currentContext.Request.RawUrl;
        }
        else
        {
          throw new Exception("HttpContext.Current is Invalid");
        }
      }
      catch (Exception e)
      {
        throw new NotSupportedException("This provider requires a valid context.",e);
      }
    }
    protected virtual void LoadSiteMapFromStore()
    {
      string pathToOpen;

      lock (this)
      {
        // If a root node exists, LoadSiteMapFromStore has already 
        // been called, and the method can return. 
        if (rootNode != null)
        {
          return;
        }
        else
        {
          pathToOpen = HttpContext.Current.Server.MapPath("~" + "\\" + sourceFilename);

          if (File.Exists(pathToOpen))
          {
            // Open the file to read from. 
            using (StreamReader sr = File.OpenText(pathToOpen))
            {

              // Clear the state of the collections and rootNode
              rootNode = null;
              siteMapNodes.Clear();
              childParentRelationship.Clear();

              // Parse the file and build the site map 
              string s = "";
              string[] nodeValues = null;
              SiteMapNode temp = null;

              while ((s = sr.ReadLine()) != null)
              {

                // Build the various SiteMapNode objects and add 
                // them to the ArrayList collections. The format used 
                // is: URL,TITLE,DESCRIPTION,PARENTURL

                nodeValues = s.Split(',');

                temp = new SiteMapNode(this,
                    HttpRuntime.AppDomainAppVirtualPath + "/" + nodeValues[0],
                    HttpRuntime.AppDomainAppVirtualPath + "/" + nodeValues[0],
                    nodeValues[1],
                    nodeValues[2]);

                // Is this a root node yet? 
                if (null == rootNode &&
                    (null == nodeValues[3] || nodeValues[3] == String.Empty))
                {
                  rootNode = temp;
                }

              // If not the root node, add the node to the various collections. 
                else
                {
                  siteMapNodes.Add(new DictionaryEntry(temp.Url, temp));
                  // The parent node has already been added to the collection.
                  SiteMapNode parentNode =
                           FindSiteMapNode(HttpRuntime.AppDomainAppVirtualPath + "/" + nodeValues[3]);
                  if (parentNode != null)
                  {
                    childParentRelationship.Add(new DictionaryEntry(temp.Url, parentNode));
                  }
                  else
                  {
                    throw new Exception("Parent node not found for current node.");
                  }
                }
              }
            }
          }
          else
          {
            throw new Exception("File not found");
          }
        }
      }
      return;
    }
  }

}

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft