SiteMapProvider Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Fournit une classe de base commune pour tous les fournisseurs de données de carte de site et un moyen pour les développeurs d’implémenter des fournisseurs de données de carte de site personnalisés qui peuvent être utilisés avec l’infrastructure de carte de site ASP.NET en tant que magasins persistants pour SiteMap les objets.
public ref class SiteMapProvider abstract : System::Configuration::Provider::ProviderBase
public abstract class SiteMapProvider : System.Configuration.Provider.ProviderBase
type SiteMapProvider = class
inherit ProviderBase
Public MustInherit Class SiteMapProvider
Inherits ProviderBase
- Héritage
- Dérivé
Exemples
L’exemple de code suivant montre comment écrire une classe qui implémente la classe abstraite SiteMapProvider . Cet exemple inclut uniquement un exemple SiteMapProvider et un exemple de fichier texte qui fonctionne avec celui-ci. Pour exécuter l’exemple, vous avez également besoin d’une entrée dans le fichier Web.config et d’une page .aspx. Vous pouvez les trouver dans la documentation de la SiteMapDataSource.SiteMapProvider propriété.
L’exemple utilise un fichier délimité par des virgules qui suit une structure attendue pour charger des informations de plan. La première ligne du fichier représente le nœud racine du site, et les lignes suivantes sont des sous-nœuds. Chaque sous-nœud identifie son nœud parent par URL. Un exemple de fichier qui répond à ces critères est illustré ci-dessous.
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
L’exemple SimpleTextSiteMapProvider fournit des exemples d’implémentations de toutes les SiteMapProvider propriétés et méthodes.
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 &&
string.IsNullOrEmpty(nodeValues[3]))
{
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;
}
}
}
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Configuration.Provider
Imports System.IO
Imports System.Security.Permissions
Imports System.Web
Namespace Samples.AspNet.VB
<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class SimpleTextSiteMapProvider
Inherits SiteMapProvider
Private parentSiteMapProvider As SiteMapProvider = Nothing
Private simpleTextProviderName As String = Nothing
Private sourceFilename As String = Nothing
Private aRootNode As SiteMapNode = Nothing
Private siteMapNodes As ArrayList = Nothing
Private childParentRelationship As ArrayList = Nothing
' A default constructor. The Name property is initialized in the
' Initialize method.
Public Sub New()
End Sub
' Implement the CurrentNode property.
Public Overrides ReadOnly Property CurrentNode() As SiteMapNode
Get
Dim currentUrl As String = FindCurrentUrl()
' Find the SiteMapNode that represents the current page.
Dim aCurrentNode As SiteMapNode = FindSiteMapNode(currentUrl)
Return aCurrentNode
End Get
End Property
' Implement the RootNode property.
Public Overrides ReadOnly Property RootNode() As SiteMapNode
Get
Return aRootNode
End Get
End Property
' Implement the ParentProvider property.
Public Overrides Property ParentProvider() As SiteMapProvider
Get
Return parentSiteMapProvider
End Get
Set(ByVal value As SiteMapProvider)
parentSiteMapProvider = Value
End Set
End Property
' Implement the RootProvider property.
Public Overrides ReadOnly Property RootProvider() As SiteMapProvider
Get
' If the current instance belongs to a provider hierarchy, it
' cannot be the RootProvider. Rely on the ParentProvider.
If Not (Me.ParentProvider Is Nothing) Then
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 Me
End If
End Get
End Property
' Implement the FindSiteMapNode method.
Public Overrides Function FindSiteMapNode(ByVal rawUrl As String) As SiteMapNode
' Does the root node match the URL?
If RootNode.Url = rawUrl Then
Return RootNode
Else
Dim candidate As SiteMapNode = Nothing
' Retrieve the SiteMapNode that matches the URL.
SyncLock Me
candidate = GetNode(siteMapNodes, rawUrl)
End SyncLock
Return candidate
End If
End Function 'FindSiteMapNode
' Implement the GetChildNodes method.
Public Overrides Function GetChildNodes(ByVal node As SiteMapNode) As SiteMapNodeCollection
Dim children As New SiteMapNodeCollection()
' Iterate through the ArrayList and find all nodes that have the specified node as a parent.
SyncLock Me
Dim i As Integer
For i = 0 To childParentRelationship.Count - 1
Dim de As DictionaryEntry = CType(childParentRelationship(i), DictionaryEntry)
Dim nodeUrl As String = CType(de.Key, String)
Dim parent As SiteMapNode = GetNode(childParentRelationship, nodeUrl)
If Not (parent Is Nothing) AndAlso node.Url = parent.Url Then
' The SiteMapNode with the Url that corresponds to nodeUrl
' is a child of the specified node. Get the SiteMapNode for
' the nodeUrl.
Dim child As SiteMapNode = FindSiteMapNode(nodeUrl)
If Not (child Is Nothing) Then
children.Add(CType(child, SiteMapNode))
Else
Throw New Exception("ArrayLists not in sync.")
End If
End If
Next i
End SyncLock
Return children
End Function 'GetChildNodes
Protected Overrides Function GetRootNodeCore() As SiteMapNode
Return RootNode
End Function ' GetRootNodeCore()
' Implement the GetParentNode method.
Public Overrides Function GetParentNode(ByVal node As SiteMapNode) As SiteMapNode
' Check the childParentRelationship table and find the parent of the current node.
' If there is no parent, the current node is the RootNode.
Dim parent As SiteMapNode = Nothing
SyncLock Me
' Get the Value of the node in childParentRelationship
parent = GetNode(childParentRelationship, node.Url)
End SyncLock
Return parent
End Function 'GetParentNode
' Implement the ProviderBase.Initialize method.
' Initialize is used to initialize the state that the Provider holds, but
' not actually build the site map.
Public Overrides Sub Initialize(ByVal name As String, ByVal attributes As NameValueCollection)
SyncLock Me
MyBase.Initialize(name, attributes)
simpleTextProviderName = name
sourceFilename = attributes("siteMapFile")
siteMapNodes = New ArrayList()
childParentRelationship = New ArrayList()
' Build the site map in memory.
LoadSiteMapFromStore()
End SyncLock
End Sub
' Private helper methods
Private Function GetNode(ByVal list As ArrayList, ByVal url As String) As SiteMapNode
Dim i As Integer
For i = 0 To list.Count - 1
Dim item As DictionaryEntry = CType(list(i), DictionaryEntry)
If CStr(item.Key) = url Then
Return CType(item.Value, SiteMapNode)
End If
Next i
Return Nothing
End Function 'GetNode
' Get the URL of the currently displayed page.
Private Function FindCurrentUrl() As String
Try
' The current HttpContext.
Dim currentContext As HttpContext = HttpContext.Current
If Not (currentContext Is Nothing) Then
Return currentContext.Request.RawUrl
Else
Throw New Exception("HttpContext.Current is Invalid")
End If
Catch e As Exception
Throw New NotSupportedException("This provider requires a valid context.", e)
End Try
End Function 'FindCurrentUrl
Protected Overridable Sub LoadSiteMapFromStore()
Dim pathToOpen As String
SyncLock Me
' If a root node exists, LoadSiteMapFromStore has already
' been called, and the method can return.
If Not (aRootNode Is Nothing) Then
Return
Else
pathToOpen = HttpContext.Current.Server.MapPath("~" & "\\" & sourceFilename)
If File.Exists(pathToOpen) Then
' Open the file to read from.
Dim sr As StreamReader = File.OpenText(pathToOpen)
Try
' Clear the state of the collections and aRootNode
aRootNode = Nothing
siteMapNodes.Clear()
childParentRelationship.Clear()
' Parse the file and build the site map
Dim s As String = ""
Dim nodeValues As String() = Nothing
Dim temp As SiteMapNode = Nothing
Do
s = sr.ReadLine()
If Not s Is Nothing Then
' Build the various SiteMapNode objects and add
' them to the ArrayList collections. The format used
' is: URL,TITLE,DESCRIPTION,PARENTURL
nodeValues = s.Split(","c)
temp = New SiteMapNode(Me, _
HttpRuntime.AppDomainAppVirtualPath & "/" & nodeValues(0), _
HttpRuntime.AppDomainAppVirtualPath & "/" & nodeValues(0), _
nodeValues(1), _
nodeValues(2))
' Is this a root node yet?
If aRootNode Is Nothing AndAlso _
(nodeValues(3) Is Nothing OrElse _
nodeValues(3) = String.Empty) Then
aRootNode = 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.
Dim parentNode As SiteMapNode = _
FindSiteMapNode(HttpRuntime.AppDomainAppVirtualPath & "/" & nodeValues(3))
If Not (parentNode Is Nothing) Then
childParentRelationship.Add(New DictionaryEntry(temp.Url, parentNode))
Else
Throw New Exception("Parent node not found for current node.")
End If
End If
End If
Loop Until s Is Nothing
Finally
sr.Close()
End Try
Else
Throw New Exception("File not found")
End If
End If
End SyncLock
Return
End Sub
End Class
End Namespace
Remarques
Les StaticSiteMapProvider classes et XmlSiteMapProvider les classes représentent les implémentations par défaut de la classe abstraite SiteMapProvider . Il XmlSiteMapProvider utilise un fichier XML nommé Web.plan pour stocker les données de la carte de site. Pour plus d’informations sur le fichier Web.plan, consultez ASP.NET Site Maps.
La SiteMapProvider classe prend en charge le concept d’une hiérarchie de fournisseur de cartes de site, en déclarant les propriétés et ParentProvider les RootProvider propriétés. Il SiteMapProvider peut s’agir d’un enfant ou d’un parent d’un autre fournisseur. Cela permet des scénarios où différentes zones de contenu d’un site sont détenues ou implémentées par différents groupes de développement qui gèrent leurs propres cartes de site et fournisseurs de cartes de site.
Tous les SiteMapProvider objets sont configurés dans les fichiers Web.config. Tous les fournisseurs de carte de site déclarés dans ces fichiers de configuration sont chargés au moment de l’exécution et sont utilisés pour charger et traiter les données de navigation de site. L’objet SiteMap , qui effectue le suivi de tous les fournisseurs qui sont disponibles par le biais de sa Providers collection de propriétés, fournit un accès programmatique aux données de navigation gérées par les fournisseurs. L’exemple de code suivant illustre le format utilisé pour déclarer un fournisseur de carte de site dans un fichier Web.config.
<siteMap defaultProvider="<name>">
<providers>
<add
name="<friendly name>"
type="<fully qualified class name>, <assembly name (optional)>"
siteMapFile = "<file name>" />
</providers>
</siteMap>
Les données de navigation de site chargées par ces fournisseurs sont utilisées par d’autres composants de l’infrastructure de carte de site, telles que les contrôles et TreeView les SiteMapPath informations de carte de site, pour afficher les informations de carte de site pour les utilisateurs.
Si vous implémentez votre propre fournisseur de cartes de site, vous pouvez placer le fichier source dans le répertoire App_Code de votre application ASP.NET, puis l’assembly sera compilé automatiquement. Vous pouvez également placer votre propre fournisseur de carte de site dans le Global Assembly Cache (GAC) et lui fournir une référence complète dans le fichier Web.config. Pour plus d’informations sur les services de compilateur, consultez Utilisation des assemblys et du Global Assembly Cache.
Notes pour les responsables de l’implémentation
Lorsque vous héritez de la SiteMapProvider classe, vous devez remplacer les membres suivants : GetRootNodeCore(), , FindSiteMapNode(String)GetChildNodes(SiteMapNode), et GetParentNode(SiteMapNode).
Constructeurs
| Nom | Description |
|---|---|
| SiteMapProvider() |
Initialise une nouvelle instance de la classe SiteMapProvider. |
Propriétés
| Nom | Description |
|---|---|
| CurrentNode |
Obtient l’objet SiteMapNode qui représente la page actuellement demandée. |
| Description |
Obtient une brève description conviviale adaptée à l’affichage dans les outils d’administration ou d’autres interfaces utilisateur (UIs). (Hérité de ProviderBase) |
| EnableLocalization |
Obtient ou définit une valeur booléenne indiquant si les valeurs localisées des SiteMapNode attributs sont retournées. |
| Name |
Obtient le nom convivial utilisé pour faire référence au fournisseur pendant la configuration. (Hérité de ProviderBase) |
| ParentProvider |
Obtient ou définit l’objet parent SiteMapProvider du fournisseur actuel. |
| ResourceKey |
Obtient ou définit la clé de ressource utilisée pour localiser SiteMapNode les attributs. |
| RootNode |
Obtient l’objet racine SiteMapNode des données de carte de site que représente le fournisseur actuel. |
| RootProvider |
Obtient l’objet racine SiteMapProvider dans la hiérarchie du fournisseur actuel. |
| SecurityTrimmingEnabled |
Obtient une valeur booléenne indiquant si un fournisseur de cartes de site filtre les nœuds de carte de site en fonction du rôle d’un utilisateur. |
Méthodes
| Nom | Description |
|---|---|
| AddNode(SiteMapNode, SiteMapNode) |
Ajoute un SiteMapNode objet à la collection de nœuds gérée par le fournisseur de cartes de site et spécifie l’objet parent SiteMapNode . |
| AddNode(SiteMapNode) |
Ajoute un SiteMapNode objet à la collection de nœuds gérée par le fournisseur de cartes de site. |
| Equals(Object) |
Détermine si l’objet spécifié est égal à l’objet actuel. (Hérité de Object) |
| FindSiteMapNode(HttpContext) |
Récupère un SiteMapNode objet qui représente la page actuellement demandée à l’aide de l’objet spécifié HttpContext . |
| FindSiteMapNode(String) |
En cas de substitution dans une classe dérivée, récupère un SiteMapNode objet qui représente la page à l’URL spécifiée. |
| FindSiteMapNodeFromKey(String) |
Récupère un SiteMapNode objet basé sur une clé spécifiée. |
| GetChildNodes(SiteMapNode) |
En cas de substitution dans une classe dérivée, récupère les nœuds enfants d’un élément spécifique SiteMapNode. |
| GetCurrentNodeAndHintAncestorNodes(Int32) |
Fournit une méthode de recherche optimisée pour les fournisseurs de cartes de site lors de la récupération du nœud pour la page actuellement demandée et l’extraction des nœuds de carte de site parent et ancêtre pour la page active. |
| GetCurrentNodeAndHintNeighborhoodNodes(Int32, Int32) |
Fournit une méthode de recherche optimisée pour les fournisseurs de carte de site lors de la récupération du nœud pour la page actuellement demandée et l’extraction des nœuds de carte de site à proximité du nœud actuel. |
| GetHashCode() |
Sert de fonction de hachage par défaut. (Hérité de Object) |
| GetParentNode(SiteMapNode) |
En cas de substitution dans une classe dérivée, récupère le nœud parent d’un objet spécifique SiteMapNode . |
| GetParentNodeRelativeToCurrentNodeAndHintDownFromParent(Int32, Int32) |
Fournit une méthode de recherche optimisée pour les fournisseurs de cartes de site lors de la récupération d’un nœud ancêtre pour la page actuellement demandée et l’extraction des nœuds descendants pour l’ancêtre. |
| GetParentNodeRelativeToNodeAndHintDownFromParent(SiteMapNode, Int32, Int32) |
Fournit une méthode de recherche optimisée pour les fournisseurs de carte de site lors de la récupération d’un nœud ancêtre pour l’objet spécifié SiteMapNode et l’extraction de ses nœuds enfants. |
| GetRootNodeCore() |
En cas de substitution dans une classe dérivée, récupère le nœud racine de tous les nœuds actuellement gérés par le fournisseur actuel. |
| GetRootNodeCoreFromProvider(SiteMapProvider) |
Récupère le nœud racine de tous les nœuds actuellement gérés par le fournisseur de carte de site spécifié. |
| GetType() |
Obtient la Type de l’instance actuelle. (Hérité de Object) |
| HintAncestorNodes(SiteMapNode, Int32) |
Fournit une méthode que les fournisseurs de cartes de site peuvent remplacer pour effectuer une récupération optimisée d’un ou plusieurs niveaux de nœuds parents et ancêtres, par rapport à l’objet spécifié SiteMapNode . |
| HintNeighborhoodNodes(SiteMapNode, Int32, Int32) |
Fournit une méthode que les fournisseurs de carte de site peuvent remplacer pour effectuer une récupération optimisée des nœuds trouvés à proximité du nœud spécifié. |
| Initialize(String, NameValueCollection) |
Initialise l’implémentation SiteMapProvider , y compris toutes les ressources nécessaires pour charger des données de carte de site à partir d’un stockage persistant. |
| IsAccessibleToUser(HttpContext, SiteMapNode) |
Récupère une valeur booléenne indiquant si l’objet spécifié SiteMapNode peut être consulté par l’utilisateur dans le contexte spécifié. |
| MemberwiseClone() |
Crée une copie superficielle du Objectactuel. (Hérité de Object) |
| RemoveNode(SiteMapNode) |
Supprime l’objet spécifié SiteMapNode de la collection de nœuds gérée par le fournisseur de cartes de site. |
| ResolveSiteMapNode(HttpContext) |
Déclenche l’événement SiteMapResolve. |
| ToString() |
Retourne une chaîne qui représente l’objet actuel. (Hérité de Object) |
Événements
| Nom | Description |
|---|---|
| SiteMapResolve |
Se produit lorsque la CurrentNode propriété est appelée. |