Export (0) Print
Expand All

ControlCachePolicy Class

Provides programmatic access to an ASP.NET user control's output cache settings.

System.Object
  System.Web.UI.ControlCachePolicy

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

public sealed class ControlCachePolicy

The ControlCachePolicy type exposes the following members.

  NameDescription
Public propertyCachedGets or sets a value indicating whether fragment caching is enabled for the user control.
Public propertyDependencyGets or sets an instance of the CacheDependency class associated with the cached user control output.
Public propertyDurationGets or sets the amount of time that cached items are to remain in the output cache.
Public propertyProviderNameGets or sets the name of the output-cache provider that is associated with a control instance.
Public propertySupportsCachingGets a value indicating whether the user control supports caching.
Public propertyVaryByControlGets or sets a list of control identifiers to vary the cached output by.
Public propertyVaryByParamsGets or sets a list of GET or POST parameter names to vary the cached output by.
Top

  NameDescription
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSetExpiresInstructs the BasePartialCachingControl control that wraps the user control to expire the cache entry at the specified date and time.
Public methodSetSlidingExpirationInstructs the BasePartialCachingControl control that wraps the user control to set the user control's cache entry to use sliding or absolute expiration.
Public methodSetVaryByCustomSets a list of custom strings that the output cache will use to vary the user control.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

The ControlCachePolicy class is used by developers in programmatic user control scenarios to specify output caching settings for user controls (.ascx files). ASP.NET embeds user controls within a BasePartialCachingControl instance. The BasePartialCachingControl class represents a user control that has output caching enabled. When you access the BasePartialCachingControl.CachePolicy property of a PartialCachingControl control, you will always receive a valid ControlCachePolicy object. 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. 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. To determine whether a UserControl instance supports caching without generating exceptions, inspect the SupportsCaching property.

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 @ OutputCache directive to enable output caching in declarative scenarios.

  • Use the PartialCachingAttribute attribute to enable caching for a user control in a code-behind file.

  • Use 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. A ControlCachePolicy instance can be successfully manipulated only between the Init and PreRender stages of the control life cycle. If you modify a ControlCachePolicy object after the PreRender 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 the Render stage). Finally, a user control instance (and therefore its ControlCachePolicy object) is only available for programmatic manipulation when it is actually rendered.

The following code example demonstrates how a user control can be loaded dynamically and manipulated programmatically at run time. The PartialCachingAttribute attribute is applied to a user control named SimpleControl, which means the user control is wrapped by a PartialCachingControl control at run time. 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. 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>

The following code example demonstrates using the SimpleControl user control from a Web Forms page. 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;
    }
}
<%@ 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>

.NET Framework

Supported in: 4.5.3, 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