SqlCacheDependencyAdmin Clase

Definición

Realiza tareas administrativas en una base de datos de SQL Server necesarias para admitir la clase SqlCacheDependency cuando se utilizan dependencias basadas en sondeo. Esta clase no puede heredarse.

public ref class SqlCacheDependencyAdmin abstract sealed
public static class SqlCacheDependencyAdmin
type SqlCacheDependencyAdmin = class
Public Class SqlCacheDependencyAdmin
Herencia
SqlCacheDependencyAdmin

Ejemplos

El ejemplo de código siguiente es una página de ASP.NET sencilla para habilitar y deshabilitar las notificaciones de cambios en SQL Server tablas de base de datos. Usa el SqlCacheDependencyAdmin objeto para administrar las notificaciones de cambios en la base de datos especificada en una cadena de conexión denominada MyConnectionString. En el ejemplo se incluyen dos archivos, un archivo .aspx que define la interfaz de usuario y un archivo de código subyacente que contiene el código fuente para los eventos de ASP.NET.

El primer ejemplo es el archivo .aspx que define la interfaz de usuario.

Importante

Este ejemplo tiene un cuadro de texto que acepta datos proporcionados por el usuario, lo que puede suponer una amenaza para la seguridad. De forma predeterminada, ASP.NET Web Pages valida que los datos proporcionados por el usuario no incluyen elementos HTML ni de script. Para más información, consulte Información general sobre los ataques mediante scripts.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="cacheDependencyAdmincs.aspx.cs"
  Inherits="cacheDependencyAdmincs" %>

<!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 runat="server">
  <meta http-equiv="Content-Type" content="text/html" />
  <title>Cache Dependency Administration</title>
</head>
<body>
  <form id="form1" runat="server">
    <table>
      <tr>
        <td colspan="2">
          Database support for change notifications:
        </td>
      </tr>
      <tr>
        <td align="center">
          <asp:Button ID="enableNotification" runat="server" Text="On" OnClick="enableNotification_Click" />
        </td>
        <td align="center">
          <asp:Button ID="disableNotification" runat="server" Text="Off" OnClick="disableNotification_Click" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:Label ID="enabledTablesMsg" runat="server" Text="Tables enabled for change notification:" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:ListBox ID="enabledTables" runat="server" SelectionMode="multiple" /><br />
          <asp:Button ID="disableTable" runat="server" Text="Disable selected table(s)" OnClick="disableTable_Click" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:Label ID="tableEnableMsg" runat="server" Text="Enable change notification on table:" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:TextBox ID="tableName" runat="server" /><br />
          <asp:Button ID="enableTable" runat="server" Text="Enable table(s)" OnClick="enableTable_Click" />
          <asp:Label id="enableTableErrorMsg" runat="server" Visible="false" />
        </td>
      </tr>
    </table>
  </form>
</body>
</html>
<%@ Page Language="VB" CodeFile="cacheDependencyAdminvb.aspx.vb"
  Inherits="cacheDependencyAdminvb"%>

<!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 runat="server">
  <meta http-equiv="Content-Type" content="text/html" />
  <title>Cache Dependency Administration</title>
</head>
<body>
  <form id="form1" runat="server">
    <table>
      <tr>
        <td colspan="2">
          Database support for change notifications:
        </td>
      </tr>
      <tr>
        <td align="center">
          <asp:Button ID="enableNotification" runat="server" Text="On" OnClick="enableNotification_Click" />
        </td>
        <td align="center">
          <asp:Button ID="disableNotification" runat="server" Text="Off" OnClick="disableNotification_Click" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:Label ID="enabledTablesMsg" runat="server" Text="Tables enabled for change notification:" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:ListBox ID="enabledTables" runat="server" SelectionMode="multiple" /><br />
          <asp:Button ID="disableTable" runat="server" Text="Disable selected table(s)" OnClick="disableTable_Click" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:Label ID="tableEnableMsg" runat="server" Text="Enable change notification on table:" />
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <asp:TextBox ID="tableName" runat="server" /><br />
          <asp:Button ID="enableTable" runat="server" Text="Enable table(s)" OnClick="enableTable_Click" />
          <asp:Label id="enableTableErrorMsg" runat="server" Visible="false" />
        </td>
      </tr>
    </table>
  </form>
</body>
</html>

El segundo ejemplo es el archivo de código subyacente que contiene el código fuente de los eventos de la página.

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.Web.Caching;

public partial class cacheDependencyAdmincs : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // Put page in default state.
    enabledTables.Visible = true;
    disableTable.Visible = true;
    enabledTablesMsg.Text = "Tables enabled for change notification:";

    tableName.Visible = true;
    enableTable.Visible = true;
    tableEnableMsg.Text = "Enable change notification on table(s):";
    enableTableErrorMsg.Visible = false;
  }

   protected void Page_PreRender(object sender, EventArgs e)
  {
    try
    {
      string[] enabledTablesList =
      SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(
        ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
      if (enabledTablesList.Length > 0)
      {
        enabledTables.DataSource = enabledTablesList;
        enabledTables.DataBind();
      }
      else
      {
        enabledTablesMsg.Text = "No tables are enabled for change notifications.";
        enabledTables.Visible = false;
        disableTable.Visible = false;
      }
    }
    catch (DatabaseNotEnabledForNotificationException ex)
    {
      enabledTables.Visible = false;
      disableTable.Visible = false;
      enabledTablesMsg.Text = "Cache notifications are not enabled in this database.";

      tableName.Visible = false;
      enableTable.Visible = false;
      tableEnableMsg.Text = "Must enable database for notifications before enabling tables";
    }
  }
  protected void enableNotification_Click(object sender, EventArgs e)
  {
    SqlCacheDependencyAdmin.EnableNotifications(
      ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
  }
  protected void disableNotification_Click(object sender, EventArgs e)
  {
    SqlCacheDependencyAdmin.DisableNotifications(
      ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
  }
  protected void disableTable_Click(object sender, EventArgs e)
  {
    foreach (ListItem item in enabledTables.Items)
    {
      if (item.Selected)
      {
        SqlCacheDependencyAdmin.DisableTableForNotifications(
          ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString,
          item.Text);
      }
    }
  }
  protected void enableTable_Click(object sender, EventArgs e)
  {
    try
    {
      if (tableName.Text.Contains(";"))
      {
        string[] tables = tableName.Text.Split(new Char[] { ';' });
        for (int i = 0; i < tables.Length; i++)
          tables[i] = tables[i].Trim();

        SqlCacheDependencyAdmin.EnableTableForNotifications(
          ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString,
          tables);
      }
      else
      {
        SqlCacheDependencyAdmin.EnableTableForNotifications(
          ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString,
          tableName.Text);
      }
    }
    catch (HttpException ex)
    {
      enableTableErrorMsg.Text = "<br />" +
        "An error occurred enabling a table.<br />" +
        "The error message was: " +
        ex.Message;
      enableTableErrorMsg.Visible = true;
    }
  }
}
Partial Class cacheDependencyAdminvb
  Inherits System.Web.UI.Page

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    'Put the page into a default state.
    enabledTables.Visible = True
    disableTable.Visible = True
    enabledTablesMsg.Text = "Tables enabled for change notification:"

    tableName.Visible = True
    enableTable.Visible = True
    tableEnableMsg.Text = "Enable change notification on table(s):"
    enableTableErrorMsg.Text = ""
  End Sub

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)
    Try
      Dim enabledTablesList As String()
      enabledTablesList = SqlCacheDependencyAdmin.GetTablesEnabledForNotifications( _
        ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
      If enabledTablesList.Length > 0 Then
        enabledTables.DataSource = enabledTablesList
        enabledTables.DataBind()
      Else
        enabledTablesMsg.Text = "No tables are enabled for change notifications."
        enabledTables.Visible = False
        disableTable.Visible = False
      End If
    Catch ex As DatabaseNotEnabledForNotificationException
      enabledTables.Visible = False
      disableTable.Visible = False
      enabledTablesMsg.Text = "Cache notifications are not enabled in this database."

      tableName.Visible = False
      enableTable.Visible = False
      tableEnableMsg.Text = "Must enable database for notifications before enabling tables."
    End Try
  End Sub
  Protected Sub enableNotification_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    SqlCacheDependencyAdmin.EnableNotifications( _
        ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
  End Sub
  Protected Sub disableNotification_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    SqlCacheDependencyAdmin.DisableNotifications( _
        ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
  End Sub
  Protected Sub disableTable_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    For Each item As ListItem In enabledTables.Items
      If item.Selected Then
        SqlCacheDependencyAdmin.DisableTableForNotifications( _
        ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString, _
        item.Text)
      End If
    Next
  End Sub
  Protected Sub enableTable_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Try
      If tableName.Text.Contains(";") Then
        Dim tables As String()
        tables = tableName.Text.Split(New [Char]() {";"c})
        For i As Integer = 0 To tables.Length - 1
          tables(i) = tables(i).Trim
        Next

        SqlCacheDependencyAdmin.EnableTableForNotifications( _
          ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString, _
          tables)
      Else
        SqlCacheDependencyAdmin.EnableTableForNotifications( _
          ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString, _
          tableName.Text)
      End If
    Catch ex As HttpException
      enableTableErrorMsg.Text = "<br />" & _
        "An error occurred enabling a table.<br />" & _
        "The error message was: " & _
        ex.Message
      enableTableErrorMsg.Visible = True
    End Try
  End Sub

End Class

Comentarios

Puede usar los métodos de esta clase para habilitar y deshabilitar mediante programación una base de datos de SQL Server y sus tablas para SqlCacheDependency las notificaciones de cambio de objetos. Además, esta clase obtiene información sobre qué tablas de una base de datos están habilitadas para las notificaciones de cambios mediante el GetTablesEnabledForNotifications método . Sin embargo, también puede usar la herramienta de línea de comandos Aspnet_regsql para administrar las notificaciones de cambios de una base de datos de SQL Server y sus tablas.

Nota

Para llamar a cualquiera de los métodos de esta clase, la cuenta que se usa para acceder a la base de datos de SQL Server debe tener permisos para crear tablas y procedimientos almacenados. Para habilitar las notificaciones en una tabla específica, debe tener permisos para crear un desencadenador de SQL Server en esa tabla. Para obtener más información sobre cómo establecer permisos en una base de datos, consulte la documentación de SQL Server. Para obtener más información sobre la cuenta usada por el proceso de ASP.NET, consulte ASP.NET Suplantación.

Métodos

DisableNotifications(String)

Deshabilita las notificaciones de cambios de SqlCacheDependency para la base de datos especificada.

DisableTableForNotifications(String, String)

Deshabilita las notificaciones de cambios de SqlCacheDependency en una tabla de una base de datos de SQL Server.

DisableTableForNotifications(String, String[])

Deshabilita las notificaciones de cambios de SqlCacheDependency en una matriz de tablas de base de datos de SQL Server.

EnableNotifications(String)

Habilita las notificaciones de cambios de SqlCacheDependency en la base de datos especificada.

EnableTableForNotifications(String, String)

Establece una conexión a la base de datos de SQL Server especificada y habilita la tabla de base de datos especificada para las notificaciones de cambios de SqlCacheDependency.

EnableTableForNotifications(String, String[])

Establece una conexión a la base de datos de SQL Server especificada y habilita la matriz especificada de tablas de base de datos para las notificaciones de cambios de SqlCacheDependency.

GetTablesEnabledForNotifications(String)

Recupera una matriz de cadena que contiene el nombre de todas las tablas habilitadas para las notificaciones de cambios en una base de datos de SQL Server.

Se aplica a

Consulte también