ControlCachePolicy 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 un accès programmatique aux paramètres de cache de sortie d’un contrôle utilisateur ASP.NET.
public ref class ControlCachePolicy sealed
public sealed class ControlCachePolicy
type ControlCachePolicy = class
Public NotInheritable Class ControlCachePolicy
- Héritage
-
ControlCachePolicy
Exemples
L’exemple de code suivant montre comment un contrôle utilisateur peut être chargé dynamiquement et manipulé par programmation au moment de l’exécution. L’attribut PartialCachingAttribute est appliqué à un contrôle utilisateur nommé SimpleControl, ce qui signifie que le contrôle utilisateur est encapsulé par un PartialCachingControl contrôle au moment de l’exécution. Les SimpleControl paramètres de mise en cache de l’objet peuvent être manipulés par programmation via son objet associé ControlCachePolicy , qui est disponible via une référence au PartialCachingControl contrôle qui l’encapsule. Dans cet exemple, la propriété est examinée pendant l’initialisation Duration de la page et modifiée à l’aide des SetSlidingExpiration méthodes et SetExpires des méthodes si certaines conditions sont remplies.
<%@ Page Language="C#" %>
<%@ Reference Control="SimpleControl.ascx" %>
<script language="C#" runat="server">
// The following example demonstrates how to load a user control dynamically at run time, and
// work with the ControlCachePolicy object associated with it.
// Loads and displays a UserControl defined in a seperate Logonform.ascx file.
// You need to have "SimpleControl.ascx" file in
// the same directory as the aspx file.
void Page_Init(object sender, System.EventArgs e) {
// Obtain a PartialCachingControl object which wraps the 'LogOnControl' user control.
PartialCachingControl pcc = LoadControl("SimpleControl.ascx") as PartialCachingControl;
// If the control is slated to expire in greater than 60 Seconds
if (pcc.CachePolicy.Duration > TimeSpan.FromSeconds(60) )
{
// Make it expire faster. Set a new expiration time to 30 seconds, and make it
// an absolute expiration if it isnt already.
pcc.CachePolicy.SetExpires(DateTime.Now.Add(TimeSpan.FromSeconds(30)));
pcc.CachePolicy.SetSlidingExpiration(false);
}
Controls.Add(pcc);
}
</script>
<%@ Page Language="VB" %>
<%@ Reference Control="SimpleControl.ascx" %>
<script language="VB" runat="server">
' The following example demonstrates how to load a user control dynamically at run time, and
' work with the ControlCachePolicy object associated with it.
' Loads and displays a UserControl defined in a seperate Logonform.ascx file.
' You need to have "SimpleControl.ascx" file in
' the same directory as the aspx file.
Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs)
' Obtain a PartialCachingControl object which wraps the 'LogOnControl' user control.
Dim pcc As PartialCachingControl
pcc = LoadControl("SimpleControl.ascx")
' If the control is slated to expire in greater than 60 Seconds
If (pcc.CachePolicy.Duration > TimeSpan.FromSeconds(60)) Then
' Make it expire faster. Set a new expiration time to 30 seconds, and make it
' an absolute expiration if it isnt already.
pcc.CachePolicy.SetExpires(DateTime.Now.Add(TimeSpan.FromSeconds(30)))
pcc.CachePolicy.SetSlidingExpiration(False)
End If
Controls.Add(pcc)
End Sub
</script>
L’exemple de code suivant illustre l’utilisation du SimpleControl contrôle utilisateur à partir d’une page Web Forms. Pour exécuter cet exemple, vérifiez que le fichier de contrôle utilisateur (.ascx), son fichier code-behind (.cs ou .vb) et la page Web Forms qui héberge le contrôle utilisateur (.aspx) se trouvent dans le même répertoire.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
[PartialCaching(100)]
public partial class SimpleControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
ItemsRemaining.Text = GetAvailableItems().ToString();
CacheTime.Text = DateTime.Now.ToLongTimeString();
}
private int GetAvailableItems()
{
SqlConnection sqlConnection = new SqlConnection
("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "GetRemainingItems";
sqlConnection.Open();
int items = (int)sqlCommand.ExecuteScalar();
sqlConnection.Close();
return items;
}
}
Imports System.Data.SqlClient
Partial Class SimpleControl
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
ItemsRemaining.Text = GetAvailableItems().ToString()
CacheTime.Text = DateTime.Now.ToLongTimeString()
End Sub
Private Function GetAvailableItems() As Integer
Dim sqlConnection As SqlConnection
Dim sqlCommand As SqlCommand
Dim items As Integer
sqlConnection = New SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;")
sqlCommand = sqlConnection.CreateCommand()
sqlCommand.CommandType = Data.CommandType.StoredProcedure
sqlCommand.CommandText = "GetRemainingItems"
sqlConnection.Open()
items = CInt(sqlCommand.ExecuteScalar())
sqlConnection.Close()
Return items
End Function
End Class
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SimpleControl.ascx.cs" Inherits="SimpleControl" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" runat="server">
<table cellspacing="15">
<tr>
<td><b>Available items: </b></td>
<td>
<asp:Label ID="ItemsRemaining" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td><b>As of: </b></td>
<td>
<asp:Label ID="CacheTime" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>
<%@ Control Language="VB" AutoEventWireup="true" CodeFile="SimpleControl.ascx.vb" Inherits="SimpleControl" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" runat="server">
<table cellspacing="15">
<tr>
<td><b>Available items: </b></td>
<td>
<asp:Label ID="ItemsRemaining" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td><b>As of: </b></td>
<td>
<asp:Label ID="CacheTime" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>
Remarques
La ControlCachePolicy classe est utilisée par les développeurs dans les scénarios de contrôle utilisateur par programmation pour spécifier les paramètres de mise en cache de sortie pour les contrôles utilisateur (fichiers .ascx). ASP.NET incorpore des contrôles utilisateur au sein d’une BasePartialCachingControl instance. La classe représente un contrôle utilisateur sur lequel la BasePartialCachingControl mise en cache de sortie est activée. Lorsque vous accédez à la BasePartialCachingControl.CachePolicy propriété d’un PartialCachingControl contrôle, vous recevrez toujours un objet valide ControlCachePolicy . Toutefois, si vous accédez à la UserControl.CachePolicy propriété d’un UserControl contrôle, vous recevez un objet valide ControlCachePolicy uniquement si le contrôle utilisateur est déjà encapsulé par un BasePartialCachingControl contrôle. S’il n’est pas encapsulé, l’objet ControlCachePolicy retourné par la propriété lève des exceptions lorsque vous tentez de le manipuler, car il n’a pas d’associé BasePartialCachingControl. Pour déterminer si une UserControl instance prend en charge la mise en cache sans générer d’exceptions, inspectez la SupportsCaching propriété.
L’utilisation de la classe est l’une des différentes façons dont vous pouvez activer la ControlCachePolicy mise en cache de sortie. La liste suivante décrit les méthodes que vous pouvez utiliser pour activer la mise en cache de sortie :
Utilisez la directive pour activer la
@ OutputCachemise en cache de sortie dans des scénarios déclaratifs.Utilisez l’attribut pour activer la PartialCachingAttribute mise en cache d’un contrôle utilisateur dans un fichier code-behind.
Utilisez la ControlCachePolicy classe pour spécifier les paramètres de cache dans les scénarios de programmation dans lesquels vous travaillez avec BasePartialCachingControl des instances qui ont été activées pour le cache à l’aide de l’une des méthodes précédentes et chargées dynamiquement à l’aide de la TemplateControl.LoadControl méthode. Une ControlCachePolicy instance peut être manipulée correctement uniquement entre les
InitPreRenderphases du cycle de vie du contrôle. Si vous modifiez un ControlCachePolicy objet après laPreRenderphase, ASP.NET lève une exception, car les modifications apportées après le rendu du contrôle ne peuvent pas affecter réellement les paramètres de cache (un contrôle est mis en cache pendant laRenderphase). Enfin, une instance de contrôle utilisateur (et donc son ControlCachePolicy objet) n’est disponible que pour la manipulation par programmation lorsqu’elle est réellement rendue.
Propriétés
| Nom | Description |
|---|---|
| Cached |
Obtient ou définit une valeur indiquant si la mise en cache de fragments est activée pour le contrôle utilisateur. |
| Dependency |
Obtient ou définit une instance de la CacheDependency classe associée à la sortie du contrôle utilisateur mis en cache. |
| Duration |
Obtient ou définit la durée pendant laquelle les éléments mis en cache doivent rester dans le cache de sortie. |
| ProviderName |
Obtient ou définit le nom du fournisseur de cache de sortie associé à une instance de contrôle. |
| SupportsCaching |
Obtient une valeur indiquant si le contrôle utilisateur prend en charge la mise en cache. |
| VaryByControl |
Obtient ou définit une liste d’identificateurs de contrôle pour varier la sortie mise en cache. |
| VaryByParams |
Obtient ou définit une liste de noms de |
Méthodes
| Nom | Description |
|---|---|
| Equals(Object) |
Détermine si l’objet spécifié est égal à l’objet actuel. (Hérité de Object) |
| GetHashCode() |
Sert de fonction de hachage par défaut. (Hérité de Object) |
| GetType() |
Obtient la Type de l’instance actuelle. (Hérité de Object) |
| MemberwiseClone() |
Crée une copie superficielle du Objectactuel. (Hérité de Object) |
| SetExpires(DateTime) |
Indique au BasePartialCachingControl contrôle qui encapsule le contrôle utilisateur d’expirer l’entrée du cache à la date et à l’heure spécifiées. |
| SetSlidingExpiration(Boolean) |
Indique au BasePartialCachingControl contrôle qui encapsule le contrôle utilisateur pour définir l’entrée de cache du contrôle utilisateur pour utiliser l’expiration glissante ou absolue. |
| SetVaryByCustom(String) |
Définit une liste de chaînes personnalisées que le cache de sortie utilisera pour varier le contrôle utilisateur. |
| ToString() |
Retourne une chaîne qui représente l’objet actuel. (Hérité de Object) |