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)

[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public abstract class SiteMapProvider : ProviderBase

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 example shows 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 to define 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. The following example shows this format.

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;
    }
  }

}

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0

Community Additions

ADD
Show:
© 2014 Microsoft