Este tema aún no ha recibido ninguna valoración - Valorar este tema

ObjectDataSource.SqlCacheDependency (Propiedad)

Actualización: noviembre 2007

Obtiene o establece una cadena delimitada por puntos y comas que indica las bases de datos y las tablas que deben utilizarse para la dependencia de caché de Microsoft SQL Server.

Espacio de nombres:  System.Web.UI.WebControls
Ensamblado:  System.Web (en System.Web.dll)
public virtual string SqlCacheDependency { get; set; }
/** @property */
public String get_SqlCacheDependency()
/** @property */
public  void set_SqlCacheDependency(String value)

public function get SqlCacheDependency () : String
public function set SqlCacheDependency (value : String)
<asp:ObjectDataSource SqlCacheDependency="String" />

Valor de propiedad

Tipo: System.String
Cadena que indica las bases de datos y las tablas que deben utilizarse para la dependencia de caché de SQL Server.

El control ObjectDataSource admite una directiva de expiración opcional que está basada en el objeto SqlCacheDependency para la caché de datos (el servicio debe configurarse para el servidor de base de datos).

SQL Server admite dos mecanismos de invalidación de la caché: el sondeo y la notificación. Cada uno tiene su propia sintaxis para el objeto SqlCacheDependency.

El objeto ObjectDataSource sólo admite el sondeo. La cadena SqlCacheDependency se utiliza para crear un objeto SqlDependency que se pasa al constructor DbCommand antes de la ejecución del método Select. La cadena SqlCacheDependency identifica las bases de datos y tablas conforme al mismo formato que utiliza la directiva @ Page, donde la primera parte de la cadena es una cadena de conexión con una base de datos de SQL Server, seguida de un delimitador de dos puntos y, por último, el nombre de la tabla de la base de datos (por ejemplo, "connectionstring1:table1"). Si la propiedad SqlCacheDependency depende de más de una tabla, los pares de cadena de conexión y nombre de tabla se separan con punto y coma (por ejemplo, "connectionstring1:table1";connectionstring2:table2").

Para admitir la notificación, debe escribir la lógica de caché en la implementación de la propiedad SelectMethod y controlar la construcción del objeto SqlCacheDependency en el código.

Esta sección contiene dos ejemplos de código. En el primer ejemplo de código se muestra cómo crear una dependencia de caché de SQL Server y establecer la propiedad SqlCacheDependency de un objeto ObjectDataSource. En el segundo ejemplo de código se muestra cómo implementar un método contenedor que devuelve un objeto DataSet para habilitar el almacenamiento en caché y el filtrado con un objeto ObjectDataSource.

En el ejemplo de código siguiente se muestra cómo crear una dependencia de caché de SQL Server y establecer la propiedad SqlCacheDependency de un control ObjectDataSource. En este ejemplo, la base de datos se interroga cada 120 segundos. Si los datos de la tabla de empleados de Northwind Traders cambian durante ese tiempo, todos los datos almacenados en caché por el control ObjectDataSource y mostrados por el control GridView expiran y se recupera un nuevo conjunto de datos en la siguiente solicitud de la página.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>

<!--
The page uses an example configuration that includes
connection strings and a defined SqlCacheDependecy.

<?xml version="1.0"?>
<configuration>

  <connectionStrings>
    <add name="MyNorthwind"
         connectionString="Data Source="localhost";Integrated Security="SSPI";Initial Catalog="Northwind""
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
    <cache>
      <sqlCacheDependency enabled="true">
        <databases>
          <add
            name="Northwind"
            connectionStringName="MyNorthwind"
            pollTime="120000" />
        </databases>
      </sqlCacheDependency>
    </cache>

  </system.web>
</configuration>
-->



<!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>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:gridview
          id="GridView1"
          runat="server"
          datasourceid="ObjectDataSource1" />

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          typename="Samples.AspNet.CS.EmployeeLogic"
          selectmethod="GetAllEmployeesAsDataSet"
          enablecaching="True"
          cacheduration="300"
          cacheexpirationpolicy="Absolute"
          sqlcachedependency="Northwind:Employees" />

    </form>
  </body>
</html>


<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.JSL" Assembly="Samples.AspNet.JSL" %>
<%@ Page language="VJ#" %>

<!--

The page uses an example configuration that includes
connection strings and a defined SqlCacheDependecy.

<?xml version="1.0"?>
<configuration>

  <connectionStrings>
    <add name = "NorthwindConnection" connectionString = "Data Source="localhost";Integrated Security="SSPI";Initial Catalog="Northwind"" />
  </connectionStrings>

  <system.web>

    ...

    <cache>
      <sqlCacheDependency enabled="true">
        <databases>
          <add
            name="Northwind_Remote"
            connectionStringName="NorthwindConnection"
            pollTime="120000" />
        </databases>
      </sqlCacheDependency>
    </cache>

  </system.web>
</configuration>
-->



<!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>
    <title>ObjectDataSource - VJ# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:gridview
          id="GridView1"
          runat="server"
          datasourceid="ObjectDataSource1" />

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          typename="Samples.AspNet.JSL.EmployeeLogic"
          selectmethod="GetAllEmployeesAsDataSet"
          enablecaching="True"
          cacheduration="300"
          cacheexpirationpolicy="Absolute"
          sqlcachedependency="Northwind_Remote:Employees" />

    </form>
  </body>
</html>


En el ejemplo de código siguiente se muestra cómo implementar un método contenedor que devuelve un objeto DataSet para habilitar el almacenamiento en caché y el filtrado con un control ObjectDataSource. En la implementación base de la clase EmployeeLogic, el método GetAllEmployees devuelve un objeto ArrayList. En lugar de refactorizar el objeto completamente para trabajar con ObjectDataSource en una página de formularios Web Forms, se agrega un método contenedor denominado GetAllEmployeesAsDataSet que devuelve un conjunto de datos NorthwindEmployee como un DataSet.

namespace Samples.AspNet.CS {

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
  //
  // EmployeeLogic is a stateless business object that encapsulates
  // the operations one can perform on a NorthwindEmployee object.
  //
  public class EmployeeLogic {

    // Returns a collection of NorthwindEmployee objects.
    public static ICollection GetAllEmployees () {
      ArrayList al = new ArrayList();

      ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];

      SqlDataSource sds
        = new SqlDataSource(cts.ConnectionString,
                            "SELECT EmployeeID FROM Employees");
      try {
        IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);

        // Iterate through the Enumeration and create a
        // NorthwindEmployee object for each ID.
        IEnumerator enumerator = IDs.GetEnumerator();
        while (enumerator.MoveNext()) {
          // The IEnumerable contains DataRowView objects.
          DataRowView row = enumerator.Current as DataRowView;
          string id = row["EmployeeID"].ToString();
          NorthwindEmployee nwe = new NorthwindEmployee(id);
          // Add the NorthwindEmployee object to the collection.
          al.Add(nwe);
        }
      }
      finally {
        // If anything strange happens, clean up.
        sds.Dispose();
      }

      return al;
    }

    //
    // To support basic filtering, the employees cannot
    // be returned as an array of objects, rather as a
    // DataSet of the raw data values.
    public static DataSet GetAllEmployeesAsDataSet () {
      ICollection employees = GetAllEmployees();

      DataSet ds = new DataSet("Table");

      // Create the schema of the DataTable.
      DataTable dt = new DataTable();
      DataColumn dc;
      dc = new DataColumn("FirstName", typeof(string)); dt.Columns.Add(dc);
      dc = new DataColumn("LastName",  typeof(string)); dt.Columns.Add(dc);
      dc = new DataColumn("Title",     typeof(string)); dt.Columns.Add(dc);
      dc = new DataColumn("Courtesy",  typeof(string)); dt.Columns.Add(dc);
      dc = new DataColumn("Supervisor",typeof(Int32));  dt.Columns.Add(dc);

      // Add rows to the DataTable.
      IEnumerator emplEnum = employees.GetEnumerator();
      DataRow row;
      NorthwindEmployee ne;
      while (emplEnum.MoveNext()) {
        ne = emplEnum.Current as NorthwindEmployee;
        row = dt.NewRow();
        row["FirstName"]  = ne.FirstName;
        row["LastName"]   = ne.LastName;
        row["Title"]      = ne.Title;
        row["Courtesy"]   = ne.Courtesy;
        row["Supervisor"] = ne.Supervisor;
        dt.Rows.Add(row);
      }
      // Add the complete DataTable to the DataSet.
      ds.Tables.Add(dt);

      return ds;
    }
    public static NorthwindEmployee GetEmployee(object anID) {
      if (anID.Equals("-1") ||
          anID.Equals(DBNull.Value) ) {
        return new NorthwindEmployee();
      }
      else {
        return new NorthwindEmployee(anID);
      }
    }

    public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
      bool retval = ne.Save();
      if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
    }

    public static void DeleteEmployee(NorthwindEmployee ne) {
      bool retval = ne.Delete();
      if (! retval) { throw new NorthwindDataException("DeleteEmployee failed."); }
    }
  }

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";
      title="";
      titleOfCourtesy = "";
      reportsTo = -1;
    }

    public NorthwindEmployee (object anID) {
      this.ID = anID;

      SqlConnection conn
        = new SqlConnection (ConfigurationManager.ConnectionStrings["NorthwindConnection"].ConnectionString);
      SqlCommand sc =
        new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
                       " FROM Employees " +
                       " WHERE EmployeeID = @empId",
                       conn);
      // Add the employee ID parameter and set its value.
      sc.Parameters.Add(new SqlParameter("@empId",SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
      SqlDataReader sdr = null;

      try {
        conn.Open();
        sdr = sc.ExecuteReader();

        // Only loop once.
        if (sdr != null && sdr.Read()) {
          // The IEnumerable contains DataRowView objects.
          this.firstName        = sdr["FirstName"].ToString();
          this.lastName         = sdr["LastName"].ToString();
          this.title            = sdr["Title"].ToString();
          this.titleOfCourtesy  = sdr["TitleOfCourtesy"].ToString();
          if (! sdr.IsDBNull(4)) {
            this.reportsTo        = sdr.GetInt32(4);
          }
        }
        else {
          throw new NorthwindDataException("Data not loaded for employee id.");
        }
      }
      finally {
        try {
          if (sdr != null) sdr.Close();
          conn.Close();
        }
        catch (SqlException) {
          // Log an event in the Application Event Log.
          throw;
        }
      }
    }

    private object ID;
    public string EmpID {
      get { return ID.ToString();  }
    }

    private string lastName;
    public string LastName {
      get { return lastName; }
      set { lastName = value; }
    }

    private string firstName;
    public string FirstName {
      get { return firstName; }
      set { firstName = value;  }
    }

    public string FullName {
      get { return FirstName + " " + LastName; }
    }

    private string title;
    public String Title {
      get { return title; }
      set { title = value; }
    }

    private string titleOfCourtesy;
    public string Courtesy {
      get { return titleOfCourtesy; }
      set { titleOfCourtesy = value; }
    }

    private int    reportsTo;
    public int Supervisor {
      get { return reportsTo; }
      set { reportsTo = value; }
    }

    public bool Save () {
      // Implement persistence logic.
      return true;
    }

    public bool Delete () {
      // Implement delete logic.
      return true;
    }
  }

  internal class NorthwindDataException: Exception {
    public NorthwindDataException(string msg) : base (msg) { }
  }
}


package Samples.AspNet.JSL;

import System.*;
import System.Collections.*;
import System.Configuration.*;
import System.Data.*;
import System.Data.SqlClient.*;
import System.Web.UI.*;
import System.Web.UI.WebControls.*;

//
// EmployeeLogic is a stateless business object that encapsulates
// the operations one can perform on a NorthwindEmployee object.
//
public class EmployeeLogic
{
    // Returns a collection of NorthwindEmployee objects.
    public static ICollection GetAllEmployees() throws NorthwindDataException
    {
        ArrayList al = new ArrayList();

		ConnectionStringSettings cts =
			ConfigurationManager.get_ConnectionStrings().get_Item("NorthwindConnection");

        SqlDataSource sds = new SqlDataSource(cts.get_ConnectionString(),
            "SELECT EmployeeID FROM Employees");
        try {
            IEnumerable ids = sds.Select(DataSourceSelectArguments.get_Empty());
            // Iterate through the Enumeration and create a
            // NorthwindEmployee object for each ID.
            IEnumerator enumerator = ids.GetEnumerator();
            while (enumerator.MoveNext()) {
                // The IEnumerable contains DataRowView objects.
                DataRowView row = (DataRowView)enumerator.get_Current();
                String idObj = row.get_Item("EmployeeID").ToString();
                NorthwindEmployee nwe = new NorthwindEmployee(idObj);
                // Add the NorthwindEmployee object to the collection.
                al.Add(nwe);
            }
        }
        finally {
            // If anything strange happens, clean up.
            sds.Dispose();
        }
        return al;
    } //GetAllEmployees

    //
    // To support basic filtering, the employees cannot
    // be returned as an array of objects, rather as a
    // DataSet of the raw data values.
    public static DataSet GetAllEmployeesAsDataSet() throws NorthwindDataException
    {
        ICollection employees = GetAllEmployees();

        DataSet ds = new DataSet("Table");
        // Create the schema of the DataTable.
        DataTable dt = new DataTable();
        DataColumn dc;
        dc = new DataColumn("FirstName", String.class.ToType());
        dt.get_Columns().Add(dc);
        dc = new DataColumn("LastName", String.class.ToType());
        dt.get_Columns().Add(dc);
        dc = new DataColumn("Title", String.class.ToType());
        dt.get_Columns().Add(dc);
        dc = new DataColumn("Courtesy", String.class.ToType());
        dt.get_Columns().Add(dc);
        dc = new DataColumn("Supervisor", Int32.class.ToType());
        dt.get_Columns().Add(dc);
        // Add rows to the DataTable.
        IEnumerator emplEnum = employees.GetEnumerator();
        DataRow row;
        NorthwindEmployee ne;
        while (emplEnum.MoveNext()) {
            ne = (NorthwindEmployee)emplEnum.get_Current();
            row = dt.NewRow();
            row.set_Item("FirstName", ne.get_FirstName());
            row.set_Item("LastName", ne.get_LastName());
            row.set_Item("Title", ne.get_Title());
            row.set_Item("Courtesy", ne.get_Courtesy());
            row.set_Item("Supervisor", (Int32)ne.get_Supervisor());
            dt.get_Rows().Add(row);
        }
        // Add the complete DataTable to the DataSet.
        ds.get_Tables().Add(dt);

        return ds;
    } //GetAllEmployeesAsDataSet

    public static NorthwindEmployee GetEmployee(Object anID)
        throws NorthwindDataException
    {
        if (anID.Equals("-1") || anID.Equals(DBNull.Value)) {
            return new NorthwindEmployee();
        }
        else {
            return new NorthwindEmployee(anID);
        }
    } //GetEmployee

    public static void UpdateEmployeeInfo(NorthwindEmployee ne)
        throws NorthwindDataException
    {
        boolean retVal = ne.Save();
        if (!(retVal)) {
            throw new NorthwindDataException("UpdateEmployee failed.");
        }
    } //UpdateEmployeeInfo

    public static void DeleteEmployee(NorthwindEmployee ne)
        throws NorthwindDataException
    {
        boolean retVal = ne.Delete();
        if (!(retVal)) {
            throw new NorthwindDataException("DeleteEmployee failed.");
        }
    } //DeleteEmployee
} //EmployeeLogic

public class NorthwindEmployee
{
    public NorthwindEmployee()
    {
        id = DBNull.Value;
        lastName = "";
        firstName = "";
        title = "";
        titleOfCourtesy = "";
        reportsTo = -1;
    } //NorthwindEmployee

    public NorthwindEmployee(Object anID) throws NorthwindDataException
    {
        this.id = anID;

		SqlConnection conn = new SqlConnection(ConfigurationManager.
			get_ConnectionStrings().get_Item("NorthwindConnection").
			get_ConnectionString());
        SqlCommand sc = new SqlCommand(" SELECT FirstName,LastName,Title,"
            + "TitleOfCourtesy,ReportsTo " + " FROM Employees "
            + " WHERE EmployeeID = @empId", conn);
        // Add the employee ID parameter and set its value.
        sc.get_Parameters().Add(new SqlParameter("@empId", SqlDbType.Int)).
            set_Value(anID.ToString());
        SqlDataReader sdr = null;

        try {
            conn.Open();
            sdr = sc.ExecuteReader();
            // Only loop once.
            if (sdr != null && sdr.Read()) {
                // The IEnumerable contains DataRowView objects.
                this.firstName = sdr.get_Item("FirstName").ToString();
                this.lastName = sdr.get_Item("LastName").ToString();
                this.title = sdr.get_Item("Title").ToString();
                this.titleOfCourtesy = sdr.get_Item("TitleOfCourtesy").ToString();
                if (!(sdr.IsDBNull(4))) {
                    this.reportsTo = sdr.GetInt32(4);
                }
            }
            else {
                throw new NorthwindDataException("Data not loaded for"
                    + " employee id.");
            }
        }
        finally {
            try {
                if (sdr != null) {
                    sdr.Close();
                }
                conn.Close();
            }
            catch (SqlException exp) {
                // Log an event in the Application Event Log.
            }
        }
    } //NorthwindEmployee

    private Object id;

    /** @property 
     */
    public String get_EmpID()
    {
        return id.ToString();
    } //get_EmpID

    private String lastName;

    /** @property 
     */
    public String get_LastName()
    {
        return lastName;
    } //get_LastName

    /** @property 
     */
    public void set_LastName(String value)
    {
        lastName = value;
    } //set_LastName

    private String firstName;

    /** @property 
     */
    public String get_FirstName()
    {
        return firstName;
    } //get_FirstName

    /** @property 
     */
    public void set_FirstName(String value)
    {
        firstName = value;
    } //set_FirstName

    /** @property 
     */
    public String get_FullName()
    {
        return get_FirstName() + " " + get_LastName();
    } //get_FullName

    private String title;

    /** @property 
     */
    public String get_Title()
    {
        return title;
    } //get_Title

    /** @property 
     */
    public void set_Title(String value)
    {
        title = value;
    } //set_Title

    private String titleOfCourtesy;

    /** @property 
     */
    public String get_Courtesy()
    {
        return titleOfCourtesy;
    } //get_Courtesy

    /** @property 
     */
    public void set_Courtesy(String value)
    {
        titleOfCourtesy = value;
    } //set_Courtesy

    private int reportsTo;

    /** @property 
     */
    public int get_Supervisor()
    {
        return reportsTo;
    } //get_Supervisor

    /** @property 
     */
    public void set_Supervisor(int value)
    {
        reportsTo = value;
    } //set_Supervisor

    public boolean Save()
    {
        // Implement persistence logic.
        return true;
    } //Save

    public boolean Delete()
    {
        // Implement delete logic.
        return true;
    } //Delete
} //NorthwindEmployee

class NorthwindDataException extends Exception
{
    public NorthwindDataException(String msg)
    {
        super(msg);
    } //NorthwindDataException
} //NorthwindDataException


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0
¿Te ha resultado útil?
(Caracteres restantes: 1500)

Adiciones de comunidad

AGREGAR
© 2013 Microsoft. Reservados todos los derechos.