ControlCachePolicy Класс
Определение
Обеспечивает программный доступ к параметрам кэша выходного потока пользовательского элемента управления ASP.NET.Provides programmatic access to an ASP.NET user control's output cache settings.
public ref class ControlCachePolicy sealed
public sealed class ControlCachePolicy
type ControlCachePolicy = class
Public NotInheritable Class ControlCachePolicy
- Наследование
-
ControlCachePolicy
Примеры
В следующем примере кода показано, как пользовательский элемент управления может динамически загружаться и управляться программно во время выполнения.The following code example demonstrates how a user control can be loaded dynamically and manipulated programmatically at run time. Атрибут применяется к пользовательскому элементу управления с SimpleControl
именем, что означает, что пользовательский PartialCachingControl элемент управления упаковывается элементом управления во время выполнения. PartialCachingAttributeThe PartialCachingAttribute attribute is applied to a user control named SimpleControl
, which means the user control is wrapped by a PartialCachingControl control at run time. Параметры кэширования ControlCachePolicyобъектаможно программно обрабатывать с помощью связанного объекта, который доступен PartialCachingControl через ссылку на элемент управления, который его заключает в оболочку. SimpleControl
The SimpleControl
object's caching settings can be programmatically manipulated through its associated ControlCachePolicy object, which is available through a reference to the PartialCachingControl control that wraps it. В этом примере Duration свойство проверяется во время инициализации страницы и изменяется SetSlidingExpiration с помощью методов и SetExpires , если выполняются некоторые условия.In this example, the Duration property is examined during page initialization and changed using the SetSlidingExpiration and SetExpires methods if some conditions are met.
<%@ 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>
В следующем примере кода показано использование SimpleControl
пользовательского элемента управления из страницы веб-форм.The following code example demonstrates using the SimpleControl
user control from a Web Forms page. Для успешного выполнения этого примера убедитесь, что файл пользовательского элемента управления (ASCX), его файл кода программной части (CS или VB) и страница веб-форм, на котором размещен пользовательский элемент управления (. aspx), находятся в одном каталоге.To run this example successfully, make sure the user control file (.ascx), its code-behind file (.cs or .vb), and the Web Forms page that hosts the user control (.aspx) are in the same directory.
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>
Комментарии
ControlCachePolicy Класс используется разработчиками в сценариях программного пользовательского управления для указания параметров кэширования выходных данных для пользовательских элементов управления (ASCX-файлов).The ControlCachePolicy class is used by developers in programmatic user control scenarios to specify output caching settings for user controls (.ascx files). ASP.NET внедряет пользовательские элементы управления в BasePartialCachingControl экземпляре.ASP.NET embeds user controls within a BasePartialCachingControl instance. BasePartialCachingControl Класс представляет пользовательский элемент управления, для которого включено кэширование вывода.The BasePartialCachingControl class represents a user control that has output caching enabled. При доступе к BasePartialCachingControl.CachePolicy свойству PartialCachingControl элемента управления всегда будет получен допустимый ControlCachePolicy объект.When you access the BasePartialCachingControl.CachePolicy property of a PartialCachingControl control, you will always receive a valid ControlCachePolicy object. UserControl.CachePolicy Однако при доступе к свойству UserControl элемента управления вы получаете допустимый ControlCachePolicy объект, только если пользовательский элемент управления уже заключен в оболочку BasePartialCachingControl элемента управления.However, if you access the UserControl.CachePolicy property of a UserControl control, you receive a valid ControlCachePolicy object only if the user control is already wrapped by a BasePartialCachingControl control. Если он не заключен в оболочку ControlCachePolicy , то объект, возвращаемый свойством, вызовет исключения при попытке управлять им, так как у BasePartialCachingControlнего нет связанного объекта.If it is not wrapped, the ControlCachePolicy object returned by the property will throw exceptions when you attempt to manipulate it because it does not have an associated BasePartialCachingControl. Чтобы определить, поддерживает UserControl ли экземпляр кэширование без создания исключений, SupportsCaching проверьте свойство.To determine whether a UserControl instance supports caching without generating exceptions, inspect the SupportsCaching property.
ControlCachePolicy Использование класса является одним из нескольких способов включения кэширования вывода.Using the ControlCachePolicy class is one of several ways you can enable output caching. В следующем списке описываются методы, которые можно использовать для включения кэширования вывода.The following list describes methods you can use to enable output caching:
Используйте директиву, чтобы включить кэширование вывода в декларативных сценариях.Use the directive to enable output caching in declarative scenarios.
PartialCachingAttribute Используйте атрибут, чтобы включить кэширование для пользовательского элемента управления в файле кода программной части.Use the PartialCachingAttribute attribute to enable caching for a user control in a code-behind file.
Используйте класс для указания параметров кэша в программных сценариях, в которых вы работаете BasePartialCachingControl с экземплярами, поддерживающими кэширование, с помощью одного из предыдущих методов TemplateControl.LoadControl и динамически загружаемых с помощью метода. ControlCachePolicyUse the ControlCachePolicy class to specify cache settings in programmatic scenarios in which you are working with BasePartialCachingControl instances that have been cache-enabled using one of the previous methods and dynamically loaded using the TemplateControl.LoadControl method. Экземпляр может быть успешно обработан только
Init
междуPreRender
этапами жизненного цикла элемента управления. ControlCachePolicyA ControlCachePolicy instance can be successfully manipulated only between theInit
andPreRender
stages of the control life cycle. Если изменить ControlCachePolicy объектPreRender
после этапа, ASP.NET создает исключение, так как любые изменения, внесенные после визуализации элемента управления, фактически не влияют на параметры кэша (элемент управления кэшируется наRender
этапе).If you modify a ControlCachePolicy object after thePreRender
phase, ASP.NET throws an exception, because any changes made after the control is rendered cannot actually affect cache settings (a control is cached during theRender
stage). Наконец, экземпляр пользовательского элемента управления (и, следовательно ControlCachePolicy , его объект) доступен только для программной манипуляции, когда он фактически подготавливается к просмотру.Finally, a user control instance (and therefore its ControlCachePolicy object) is only available for programmatic manipulation when it is actually rendered.
Свойства
Cached |
Возвращает и задает значение, показывающее, разрешено ли фрагментарное кэширование для пользовательского элемента управления.Gets or sets a value indicating whether fragment caching is enabled for the user control. |
Dependency |
Получает или задает экземпляр класса CacheDependency, связанный с кэшированным выводом пользовательского элемента управления.Gets or sets an instance of the CacheDependency class associated with the cached user control output. |
Duration |
Возвращает или устанавливает время, в течение которого кэшируемые элементы должны оставаться в кэше выходного потока.Gets or sets the amount of time that cached items are to remain in the output cache. |
ProviderName |
Получает или задает имя поставщика кэша вывода, связанного с экземпляром элемента управления.Gets or sets the name of the output-cache provider that is associated with a control instance. |
SupportsCaching |
Возвращает значение, указывающее, поддерживает ли пользовательский элемент управления кэширование.Gets a value indicating whether the user control supports caching. |
VaryByControl |
Возвращает или задает список идентификаторов элемента управления, с помощью которых выполняется сортировка выходных данных кэша.Gets or sets a list of control identifiers to vary the cached output by. |
VaryByParams |
Возвращает или задает список имен параметров |
Методы
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
GetHashCode() |
Служит в качестве хэш-функции по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
SetExpires(DateTime) |
Указывает элементу управления BasePartialCachingControl, который создает оболочку для пользовательского элемента управления, дату и время завершения кэширования.Instructs the BasePartialCachingControl control that wraps the user control to expire the cache entry at the specified date and time. |
SetSlidingExpiration(Boolean) |
Указывает элементу управления BasePartialCachingControl, который создает оболочку для пользовательского элемента управления, задать для последнего скользящее или абсолютное завершение времени кэширования.Instructs the BasePartialCachingControl control that wraps the user control to set the user control's cache entry to use sliding or absolute expiration. |
SetVaryByCustom(String) |
Задает список пользовательских строк, используемых кэшем выходного потока для изменения пользовательского элемента управления.Sets a list of custom strings that the output cache will use to vary the user control. |
ToString() |
Возвращает строку, представляющую текущий объект.Returns a string that represents the current object. (Унаследовано от Object) |